ASP.NET MVC 4 C#HttpPostedFileBase,EntityValidationErrors保存到DB

时间:2014-08-05 05:36:43

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

在我的数据库中,我的FileLocation是VarChar(Max)我不确定导致此EntityValidationErrors -System.Data.Entity.Validation.DbEntityValidationException的原因:一个或多个实体的验证失败。 db.SaveChanges()函数运行时会发生此错误;

型号:

   public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }

    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public string FileLocation  { get; set; }

    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}

控制器:

        [HttpPost]
      public ActionResult Create(Assignment assignment)
    {
    if (ModelState.IsValid)
    {

        if (Request.Files.Count > 0)
        {
            HttpPostedFileBase assignmentFile = Request.Files[0];
            if (assignmentFile.ContentLength > 0)
            {
                var fileName = Path.GetFileName(assignmentFile.FileName);
                assignment.FileLocation = Path.Combine(Server.MapPath("~/Content/Image"), fileName);
                assignmentFile.SaveAs(assignment.FileLocation);
            }


        }
            db.Assignments.Add(assignment);        
            db.SaveChanges();    
            return RedirectToAction("Index");
    }
    return View(assignment);
}

查看:

<% using (Html.BeginForm("Create", "Assignment", FormMethod.Post, new { enctype = "multipart/form-data" }))
  <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
  <%: Html.ValidationMessageFor(model => model.FileLocation) %>

2 个答案:

答案 0 :(得分:3)

是否提到哪个列会截断数据?您尝试保存到该列的数据太长,即长于定义的最大长度。

答案 1 :(得分:0)

检查数据库并确保正确配置其他列。如果尚未为数据库中各自的列正确设置数据类型和/或数据长度,则状态,注释和标记都可能导致问题。