避免实体验证错误 - 实体框架MVC 3

时间:2014-01-02 14:31:38

标签: c# asp.net-mvc-3 entity-framework

所有

我有2个视图模型(2个不同的页面),它们都包含并需要一个需要属性的模型类(NewClub),但在第二个视图之前不需要其中一些必需的属性。基本上视图#1更新/插入模型类NewClub中的一些属性,视图#2插入/更新模型类NewClub中的其他属性。

我尝试在视图#1控制器中忽略视图#1中不需要的必需属性,如下所示:

 ModelState.Remove("NewClub.ClubCounselorContact");
  ModelState.Remove("NewClub.ClubCounselorEmail");
  ModelState.Remove("NewClub.ClubCounselorPhone");

这使模型状态验证通过,但是当我去保存时:

                model.NewClub.NewClubType = model.ClubTypeSelected;
                db.NewClubs.Add(model.NewClub);
                db.Entry(model.NewClub).State = EntityState.Modified;
 try
      {
           var dbResult = db.SaveChanges() > 0;

      }

我明白了:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

有没有办法解决这个问题?

由于

示例:

 public  class NewClub
    {

        public string ClubCounselorMasterCustomerId { get; set; }

        //Used only on view page #2
        [Display(Name = "Club counselor")]
        [Required(ErrorMessage = "Club counselor name")]
        public string ClubCounselorContact { get; set; }

        //Used only on view page #2
        [Display(Name = "Club counselor email")]
        [Required(ErrorMessage = "Club counselor email")]
        public string ClubCounselorEmail { get; set; }

        //Used only on view page #2
        [Display(Name = "Club counselor phone")]
        [Required(ErrorMessage = "Club counselor phone")]
        public string ClubCounselorPhone { get; set; }

        [...]

}



  //View Model #1
  public class LetsGetStartedViewModel
    {
        public NewClub NewClub { get; set; }
        public bool HasExistingBuildingClubs { get; set; }
        [...]
}


//View Model #2
public class FormANewClubTeamViewModel
    {

        public NewClub NewClub { get; set; }
        public List<NewClubSponsor> Sponsors { get; set; }
        [...]
    }

2 个答案:

答案 0 :(得分:4)

这里真正的问题是你没有利用视图模型的强大功能。这就是为什么在您的视图中使用您的域模型不是一个好主意,因为如果您的视图具有不同的验证要求,则您无法灵活地对其进行任何操作。

因此,我建议的不是直接在视图模型中使用NewClub,而是在视图模型中添加属性以表示NewClub所需的属性。这样,您可以使用每个单独视图的数据注释来装饰这些属性,这意味着您的验证规则可能会发生变化。之后,将视图模型中的属性映射回域模型。

举个例子:

public class LetsGetStartedViewModel
{
    [Required]
    public string ClubCounselorContact { get; set; }
}

public class FormANewClubTeamViewModel
{
    public string ClubCounselorContact { get; set; }
}

然后您的控制器可能如下所示:

[HttpPost]
public ActionResult SomeAction(LetsGetStartedViewModel model)
{
    if (ModelState.IsValid)
    {
        // map properties onto a NewClub, then add it to db or whatever
        NewClub newClub = new NewClub
        {
            ClubCounselorContact = model.ClubCounselorContact
        };

        // add to database

        return RedirectToAction("Success");
    }

    return View(model);
}

答案 1 :(得分:1)

你写道:

  

必需属性但其中一些必需属性不是   需要到第二个视图

这意味着您的模型不同,因此每个View都应该有自己的模型;每个都有正确的Required标记。

是的,它需要复制/粘贴,但(1)这是迄今为止最简单的解决方案,(2)它在概念上也是正确的:不同视图的不同要求意味着不同的模型。

相关问题