RSS

Entity Framework Validation Exception

27 Apr

One of the beauty of using Entity Framework is that it will throw out validation exception based on the database required columns and data type. This means, we don’t need to set any validation rules in application level. Entity Framework will check the rules in database and throw exception based on these rules.

When validation exception is thrown, we can access Entity Framework exception from DbEntityValidationException class, as the following:

try
{
    db.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var entityValidationError in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity Type \"{0}\", Entity State \"{1}\", Errors:", entityValidationError.Entry.Entity.GetType().Name, entityValidationError.Entry.State);
        foreach (var validationError in eve.ValidationErrors)
        {
            Console.WriteLine("Property Name: \"{0}\", Error Message: \"{1}\"", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}

Or, instead of using try { } catch { }, we can also call GetValidationErrors method to get list of validation errors.
GetValidationErrors method is inherited from DbContext class. So, if you are using code generation, you will need to use DbContext Generator in order to access this method.

var validationErrors = db.GetValidationErrors();

Code is tested in Entity Framework 4.3.1

Source: MSDN

Advertisements
 
1 Comment

Posted by on April 27, 2012 in General

 

Tags: , ,

One response to “Entity Framework Validation Exception

  1. Fredrik Stipps

    July 4, 2013 at 7:45 am

    Thank you, that was exactly what I was looking for. Works as well with EF 5.0.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: