如何使Entity Framework属性不为空,但在表单提交中不是必需的 [英] How to make an Entity Framework property NOT NULL, but not required in form submission

查看:204
本文介绍了如何使Entity Framework属性不为空,但在表单提交中不是必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有代码优先模型的Entity Framework 4.1。一个常见的模式是许多对象引用拥有它们的用户,例如。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆