Wednesday 17 October 2012

How to find out EF EntityValidationErrors

Entitiy Framework find out EntityValidationErrors

Often when I am working with EF I am caught by error in validation when saving data.

When you have something like :

 var user = DbContext.Logins.FirstOrDefault(x => x.Email == userName);
 if(user !=null){
   user.LastLoginDate = DateTime.Now;
   DbContext.SaveChanges();
 }

And when saving into the database I get exception:
{"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."}

So How to find out this?

surround the code with try catch and catch exception: DbEntityValidationException

try
{
    // code...

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}


Source for this article:
stack overflow: http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert

No comments:

Post a Comment