EF ComplexType和验证

时间:2011-12-28 15:34:37

标签: asp.net-mvc-3 entity-framework validation

我在EF模型中遇到验证问题,我似乎无法弄明白。不引人注目的Javascript验证部分按预期工作。

考虑以下模型(RequiredIf属性来自this library):

public class Conversation
{
    public int Id { get; set; }
    public User User { get; set; }
    public String Handler { get; set; }
}

[ComplexType]
public class User
{
    public bool Anonymous { get; set; }
    [RequiredIf("Anonymous", false)]
    [Display(Name = "Full name")]
    public String Name { get; set; }
}

我的编辑器视图仅显示User的字段,这是我的控制器。

    [HttpPost()]
    public ActionResult Create(Conversation conversation)
    {
        if (ModelState.IsValid)
        {
            _db.Conversations.Add(conversation);
            _db.SaveChanges(); // fails on this line
        }
        return RedirectToAction("Index");
    }

这会导致以下错误:

DbUnexpectedValidationException: An unexpected exception was thrown during validation of 'Full name' when invoking Mvc.ValidationToolkit.RequiredIfAttribute.IsValid. See the inner exception for details.

内在的例外:

Member 'Conversation.Anonymous' not found.

为什么验证会突然寻找Conversation.Anonymous,而不是Conversations.Client.Anonymous

1 个答案:

答案 0 :(得分:2)

您不应该在视图中直接使用您的实体。创建特定于视图的视图模型,然后使用AutoMapper之类的东西将域对象映射到视图模型。将所有必需,长度等验证放在视图模型上。

var model = Mapper.Map<Conversation, ConversationViewModel>(conversation);

return View(model);