How to make an Entity Framework property NOT NULL,

2019-08-05 07:21发布

问题:

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.

回答1:

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.