How to make an Entity Framework property NOT NULL, but not required in form submission

吃可爱长大的小学妹 提交于 2019-12-11 13:48:31

问题


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.



来源:https://stackoverflow.com/questions/12137902/how-to-make-an-entity-framework-property-not-null-but-not-required-in-form-subm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!