Search code examples
c#asp.net-mvcasp.net-mvc-3asp.net-mvc-4httppostedfilebase

ASP.NET MVC 4 C# HttpPostedFileBase, EntityValidationErrors Save into DB


In my database My FileLocation is VarChar(Max) I not sure what caused this EntityValidationErrors -System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. This error occurs when db.SaveChanges() function run;

Model:

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

Controller:

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

View:

<% 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) %>

Solution

  • Does it mention which column would have the data truncated? The data you're trying to save into that column is too long, that is, longer than the defined maximum length.