【问题标题】:EF ComplexType and validationEF ComplexType 和验证
【发布时间】:2011-12-28 15:34:36
【问题描述】:

我在 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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      相关资源
      最近更新 更多