【问题标题】:DbEntityValidationException Error in my controller action我的控制器操作中的 DbEntityValidationException 错误
【发布时间】:2015-10-13 10:20:02
【问题描述】:

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

    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 错误。您的帮助将不胜感激。

【问题讨论】:

  • 在 VS 中检查设置“中断所有异常”,然后您可以检查 DbEntityValidationException 中包含的真实消息。在此处查看有关故障排除的更多信息stackoverflow.com/a/15820506/61577
  • 另外请记住,“真正的”错误始终隐藏在 EntityValidationErrors 集合中,而不是异常消息本身。
  • 你能告诉我 objBs.teamBs.Insert(objTeam);抛出异常
  • @Manraj: 是的 objBs.teamBs.Insert(ojbTeam);抛出异常
  • 如果你首先使用代码,你必须进行迁移

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


【解决方案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

例如

  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; }
}

【讨论】:

  • 感谢您的回复。在使用您的代码块后,它实际上显示了此错误。 sb = {Entity:'BOL.team' 属性:'teamPicture' 错误:'字段 teamPicture 必须是字符串或数组类型,最大长度为'50'。'现在,数据库中的teamPicture 是字符串类型。我已将字符串长度更改为 nVarChar(Max)。我仍然有同样的错误。我现在能做什么?
  • 你是否在实体上的代码“[MaxLength(500)]”中更改了“teamPicture”……例如,搜索 Entity:'BOL.team 并检查周围的代码。即必须是字符串并且设置了“[MaxLength()]”。你是先用代码吗?您的属性是否有 MaxLength 或者您是否使用映射来配置....
  • 使用 [MaxLength(500)] 后出现此错误。无法将“System.Web.HttpPostedFileWrapper”类型的对象转换为“System.Array”
  • 好的,但我相信这回答了你的问题?那不是一个新问题吗?我不介意帮忙,但是...它与我已经回答的原始版本有所不同,无论如何,您在哪一行收到该错误...?
  • 只是为了踢,把“[Required(ErrorMessage = "Please Upload Team Picture")]" off "public HttpPostedFileBase TeamPicture { get; set; }" 因为这对我来说没有意义。跨度>
猜你喜欢
  • 2021-11-26
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 2021-08-08
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
相关资源
最近更新 更多