'db.SaveChange EntityValidationErrors Exception
I have a problem with my program: I get my data from a database and I am trying to create a new personnel with a Button and add it to the list in the first column, but I am getting an exception.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Here is my code:
private void neuespersonal_Click_1(object sender, RoutedEventArgs e)
{
Personal p = new Personal();
p.Vornameh4 = "Neues Personal";
p.Nachnameq5 = "Nachname";
Bestellungen b = new Bestellungen();
b.Bestelldatumh8 = new DateTime(1982,05,21);
p.Bestellungens.Add(b);
db.Personals.Add(p);
db.SaveChanges(); //i get the Exception here
personal.Items.Refresh();
}

Solution 1:[1]
You will get this when you attempt to save an entity with data that does not validate against the model. I would check the properties on the model accept the data you are trying to populate.
Solution 2:[2]
Check your web.config. Perhaps you have some kind of error in your connection string.
Solution 3:[3]
I have found the following mechanic to be useful.
Make sure you have the following:
using System.Data.Entity.Validation;
Within the function that commits the save:
private void SaveDataFunction()
{
// entry input validation, rules check and the like
// now the save this is an example for new record insert (LINQ)
try
{
MyDBTable _rec = new MyDBTable;
_rec.FieldName = "Some Value";
db.MyDBTable.Add(_rec);
db.SaveChanges();
}
catch (DbEntityValidationException dbx)
{
string _msg = "Record count not be saved. The following validation errors occurred:";
int _ctr = 1;
foreach(DbEntityValidationResult _err in dbx.EntityValidationErrors)
{
foreach(DbValidationError _thisErr in _err.ValidationErrors)
{
_msg = string.Format("{0}\nError: {1}. {2} on {3}", _msg, _ctr.ToString(),_thisErr.ErrorMessage, _thisErr.PropertyName);
_ctr++;
}
}
MessageBox.Show(_msg);
}
catch (Exception ex) //optional or you could add other Exception types depending on circumstances
{
MessageBox.Show("record could not be saved. \n" + ex.Message);
}
}
Other things to consider is having an Errors Container class. How you might use this as a place to hold the DbException and a container property to hold the failed items. This allows the user to interact, correct and reattempt the save. Just a thought.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jack Gardner |
| Solution 2 | Luis Gouveia |
| Solution 3 | Paul Wichtendahl |
