如何使Entity Framework属性不为空,但在表单提交中不是必需的 [英] How to make an Entity Framework property NOT NULL, but not required in form submission
问题描述
public class Item
{
public User Owner {get;组; }
}
这在DB中创建一个可空的列,但是由于每个项目必须我希望列标记为NOT NULL的所有者。如果我使用 [必需]
属性,则提交表单以创建项目会导致错误。
通常建议为此创建单独的视图模型的情况。将数据库模型用作输入表单的视图模型被视为反模式。
创建一个 ItemViewModel
,其属性与 Item
和相关数据验证属性。您可能需要使用一个名为 Automapper 的库来自动化无聊的属性 - 那些需要的复制代码案例。
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.
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.
这篇关于如何使Entity Framework属性不为空,但在表单提交中不是必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!