1

I'm using Entity Framework 4.1 with a code-first model. A common pattern is that many objects reference the user who owns them, eg.

public class Item
{
    public User Owner { get; set; }
}

This creates a nullable column in the DB, but since every Item must have an owner I want the column marked NOT NULL. If I use the [Required] attribute then submitting the form to create an Item results in an error. That field is never set through a form, only manually in code.

EM0
  • 5,369
  • 7
  • 51
  • 85

1 Answers1

3

It is generally recommended to create separate view models for such situations. Using database models as view models for input forms is seen as an anti-pattern.

Make a ItemViewModel that has the same properties as Item and relevant data validation attributes. You may want to use a library called Automapper to automate the boring property-copy-code needed in those cases.

bjorncs
  • 1,250
  • 11
  • 20
  • 2
    Thanks, but that sounds like it will create more problems than it will solve. And the problem I want to solve is really a minor one. So, the anti-pattern aside, is there any other way to mark the column "not null"? – EM0 Aug 28 '12 at 03:24
  • @EM Your EF model is the gatekeeper to the database. If anything is required you mark it required. A view model is the way to go here. Solutions, even small ones, nowadays usually contain lots of view models and DTO's. Organization is the key. – Gert Arnold Aug 28 '12 at 07:12