While using EF 4.1 code-first
to insert data into a SQL Server database. If there is a validation error, EF
throws a DbEntityValidationException
whose EntityValidationsErrors contains the details of the issue.
For example you have set one
field as required while creating model, but while saving data in that entity
user have supplied Null value to that required field, EF throws a DbEntityValidationException.
There can be many other validation errors as well, and to see what exactly
error EF is throwing, you can write you SaveChanges method in try..catch
block as:
try
{
dbContext.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var error in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state
\"{1}\" has the following validation errors:",
error.Entry.Entity.GetType().Name,
error.Entry.State);
foreach (var ve in error.ValidationErrors)
{
Console.WriteLine("-Property: \"{0}\", Error:
\"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
|
EntityValidationErrors is a collection which
represents the entities which couldn't be validated successfully, and the inner
collection ValidationErrors per entity is a list of errors on property
level.
These validation messages are usually helpful enough to find
the source of the problem. I have simply write these errors with the help of Console.WriteLine, however you can write error in
error log file or anywhere else you want as per your requirement.
It don't working.
ReplyDelete