How to make the Entity Framework property NOT NULL, but not required when submitting the form

I am using Entity Framework 4.1 with a coded first model. A common example is that many objects refer to the user who owns them, for example.

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

This creates a column with a null value in the database, but since each item must have an owner, I want the column to be marked NOT NULL. If I use the [Required] attribute, then submitting the form to create the element results in an error. This field is never set through the form, only manually in the code.

+1
source share
1 answer

It is generally recommended that you create separate view models for such situations. Using database models as presentation models for input forms is considered an anti-pattern.

Make an ItemViewModel that has the same properties as the Item and the corresponding data validation attributes. You can use a library called Automapper to automate the required copy code needed in these cases.

+2
source

All Articles