Entity Framework Validation Exception

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:

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

1 thought on “Entity Framework Validation Exception”

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