0

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 ID was assigned 0. 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?

WosController.cs

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

        return View(wo);
    }

Wo.cs

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; }
}
5
  • 1
    getting a validation error.. what is the error? Commented Sep 6, 2016 at 18:27
  • And what does your Wo class look like? Commented Sep 6, 2016 at 18:28
  • 2
    with that error message.. how is it even working? what is e? that should be a compile-time error, not a run-time error? To get a better description of the error, why don't you try a try-catch block and catch the exception.. then when you debug it will tell you exactly what happened. Commented Sep 6, 2016 at 18:35
  • I wonder if there's something else going on. If you make your own Wo (in-code) and try to save it does it work? I wonder if there's something off about your db model Commented Sep 6, 2016 at 18:38
  • The ID of 0 is because it is a new Wo. That tells Entity Framework to perform an INSERT instead of an UPDATE. Commented Sep 6, 2016 at 18:40

2 Answers 2

1

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

try
{
    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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok it shows that the 'status' field is required. I didn't include that field since it will has a default value defined in the SQL server DB. Why is it looking for that field if there is a default in the DB?
@Beengie As of right now, your application doesn't know that there is a default value waiting for status in the database.. but you still need to include it in your bind. so just add status at the end of your binding.. like so: [Bind(Include = "id,woNumber,woDescription,dueDate,qty,item_id,releaseDate,parentWO_id,wip_id, status")] Wo wo)
1

Likely, your database is out of sync with your entities. The status property is not required on your entity, and by default properties of type string are nullable. That would explain why you're passing validation on post, but failing on actually saving the entity.

Generally, it's best not to rely on the database setting a default value in the first place. Instead, have the property itself have a default value, and then it will always be fine, regardless of what's going on at the database level:

private string _status;
public string status
{
    get { return _status ?? "Default Value"; }
    set { _status = value;
}

Short of that, if status is truly not required, then you should ensure that the status column on your table is nullable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.