DbEntityValidationException我的控制器操作

时间:2015-10-13 10:20:02

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我有一个包含四个字段的表单,其中一个是文件字段类型。我还有一个具有以下属性的团队:

    public int teamID { get; set; }
    public string teamName { get; set; }
    public string teamPicture { get; set; }
    public string description { get; set; }
    public string content { get; set; }

我创建了一个具有以下属性的ViewModel,以便启用文件上传和验证属性。

public class TeamVM
{
    [Required(ErrorMessage = "Please Enter Your Team Name")]
    [Display(Name = "Team Name")]
    public string TeamName { get; set; }

    [DisplayName("Team Picture")]
    [Required(ErrorMessage = "Please Upload Team Picture")]
    [ValidateFile]
    public HttpPostedFileBase TeamPicture { get; set; }

    [Required]
    [Display(Name = "Description")]
    public string Description { get; set; }

    [Required(ErrorMessage = "Please Enter Team Content")]
    [Display(Name = "Contenting")]
    [MaxLength(500)]
    public string Content { get; set; }
}

我有一个用于上传文件的自定义数据注释验证器

// Customized data annotation validator for uploading file
public class ValidateFileAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        int MaxContentLength = 1024 * 1024 * 3; //3 MB
        string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png" };

        var file = value as HttpPostedFileBase;

        if (file == null)
            return false;
        else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
        {
            ErrorMessage = "Please upload Your Photo of type: " + string.Join(", ", AllowedFileExtensions);
            return false;
        }
        else if (file.ContentLength > MaxContentLength)
        {
            ErrorMessage = "Your Photo is too large, maximum allowed size is : " + (MaxContentLength / 1024).ToString() + "MB";
            return false;
        }
        else
            return true;
    }
}

在我的控制器中,我通过使用HttpGet请求来使用TeamVM,以使TeamVM模型可供使用。

    [HttpGet]
    public ActionResult Create()
    {
        TeamVM model = new TeamVM();
        return View(model);
    }

然后我在TeamVM的Create Action中使用了该模型,如下所示:

    [HttpPost]
    public ActionResult Create(TeamVM model)
    {

        try
        {
                var fileName = Path.GetFileName(model.TeamPicture.FileName);
                var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
                model.TeamPicture.SaveAs(path);


                team objTeam = new team
                {
                    teamName = model.TeamName,
                    teamPicture = path,
                    description = model.Description,
                    content = model.Content
                };
                objBs.teamBs.Insert(objTeam);
                TempData["Msg"] = "Created Successfully!";                    
                return RedirectToAction("Index");
        }
        catch (DbEntityValidationException e1)
        {
            TempData["Msg"] = "Create Failed! :" + e1.Message;
            return RedirectToAction("Index");
        }
    }

但是我在代码的以下部分得到了错误:

                team objTeam = new team
                {
                    teamName = model.TeamName,
                    teamPicture = path,
                    description = model.Description,
                    content = model.Content
                };

我不知道DbEntityValidationException错误是什么。我们将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这个我会帮忙

catch (DbEntityValidationException dbEx)
{
    var sb = new StringBuilder();
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'",
                              validationErrors.Entry.Entity.GetType().FullName,
                              validationError.PropertyName,
                              validationError.ErrorMessage));
        }
    }
    throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx);
}

你也需要

ModelState.IsValid

e.g

  try
  {

     if (ModelState.IsValid)
     {
           var fileName = Path.GetFileName(model.TeamPicture.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
                model.TeamPicture.SaveAs(path);


           team objTeam = new team
           {
               teamName = model.TeamName,
               teamPicture = path,
               description = model.Description,
               content = model.Content
           };
           objBs.teamBs.Insert(objTeam);
           TempData["Msg"] = "Created Successfully!";                    
           return RedirectToAction("Index");
       }

       //the view model is NOT valid
       return View(model)

   }
   catch (DbEntityValidationException dbEx)
   {
       var sb = new StringBuilder();
       foreach (var validationErrors in dbEx.EntityValidationErrors)
       {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'",
                              validationErrors.Entry.Entity.GetType().FullName,
                              validationError.PropertyName,
                              validationError.ErrorMessage));
             }
       }
                  //throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx);

            TempData["Msg"] = sb.ToString();
            return RedirectToAction("Index");
    }

<强>更新

改变你的Team实体类,记得改变数据库......但我相信你已经做到了......

没有注释的默认值为50,谷歌此更多信息

public class Team 
{
    public int teamID { get; set; }
    public string teamName { get; set; }
    [MaxLength]
    public string teamPicture { get; set; }
    public string description { get; set; }
    public string content { get; set; }
}