Beengie Beengie - 4 months ago 52
C# Question

MVC 5 Create Validation error but valid ModelState

I am trying to create within MVC 5 and am getting a validation error even though the ModelState is coming back valid.

Error message

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

and when I look at the message, it shows....

The name 'e' does not exist in the current context

When I look at the POST data, the model that was created has all required fields filled in. I did notice that the model
was assigned
. I'm not sure if that is the error or if it is supposed to pass a zero for the ID.

What might the problem be?


public async Task<ActionResult> Create([Bind(Include = "id,woNumber,woDescription,dueDate,qty,item_id,releaseDate,parentWO_id,wip_id")] Wo wo)
if (ModelState.IsValid)
await db.SaveChangesAsync();
return RedirectToAction("Index");

return View(wo);


public partial class Wo
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Wo()
this.WoParts = new HashSet<WoPart>();
this.WoStatuses = new HashSet<WoStatus>();

public int id { get; set; }
public string woNumber { get; set; }
public string woDescription { get; set; }
public Nullable<System.DateTime> dueDate { get; set; }
public string qty { get; set; }
public Nullable<int> item_id { get; set; }
public Nullable<System.DateTime> releaseDate { get; set; }
public string status { get; set; }
public Nullable<int> parentWO_id { get; set; }
public int wip_id { get; set; }
public Nullable<int> part_id { get; set; }

public virtual Item Item { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WoPart> WoParts { get; set; }
public virtual Wo woParentWO { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WoStatus> WoStatuses { get; set; }
public virtual Part Part { get; set; }
public virtual Wip Wip { get; set; }


Wrap your call to SaveChangesAsync in a try...catch like so:

    await db.SaveChangesAsync();
catch (DbEntityValidationException e)
    var errorMessages = e.EntityValidationErrors
        .SelectMany(x => x.ValidationErrors)
        .Select(x => x.ErrorMessage);
    var fullErrorMessage = string.Join("; ", errorMessages);
    var exceptionMessage = string.Concat(e.Message, " The validation errors are: ", fullErrorMessage);
    throw new DbEntityValidationException(exceptionMessage, e.EntityValidationErrors);

That will show you the actual properties causing the validation issues. Then, update your question with the results, if you still need assistance.