Guzzyman
Guzzyman

Reputation: 561

DbEntityValidationException Error in my controller action

I have a form with four fields with one being of type file field. I also have a team with the following properties:

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

I created a ViewModel with the following properties so as to enable file upload and to validate the properties.

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

I have a customized data annotation validator for uploading file

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

In my controller, I made use of the TeamVM by using a HttpGet request to make the TeamVM model available for use.

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

I then used the model in the Create Action of the TeamVM as shown below:

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

But I get the error in the following portion of the code:

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

I don't know what is coursing the DbEntityValidationException error. Your help will be appreciated.

Upvotes: 0

Views: 663

Answers (1)

Seabizkit
Seabizkit

Reputation: 2415

this i will help

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

also you need

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

update

change your Team entity class like so, remember to change the DB as well... but i believe you have already done this...

The default without an annotation is 50, google this for more info

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

Upvotes: 1

Related Questions