Wednesday, May 16, 2012

Which property caused "System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." exception?

Sometimes when using ASP.NET MVC 3 / 4 with Entity Framework it can be difficult to see exactly which property is causing issues when db.SaveChanges() is called.

If you wrap the db.SaveChanges() in an appropriate try {} catch {} block whilst debugging (see below) each property in conflict will be written to your debug console which is much more helpful in finding and resolving the problem!

Don't forget to remove the try catch block after your debugging session though otherwise exceptions will be swallowed and disappear in a live environment which will then hinder further debugging efforts!

[Authorize(Roles = "SomeRole")]
public ActionResult Create(string SomethingsName)
    if (ModelState.IsValid)
        db.Something.Add(new Something()
            Id = Guid.NewGuid()
            Name = SomethingsName
        catch (DbEntityValidationException dbEx)
            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    Debug.WriteLine("Property: {0} Error: {1}",
                               validationError.PropertyName,validationError.ErrorMessage);                 }
    return RedirectToAction("Index");

No comments: