DbEntityValidationException: Which Properties Are Failing Validation?

Just a little quick tip to make your life easier. You'll get a DbEntityValidationException when Entity Framework attempts to save an entity to the database and fails because one or more properties are invalid. However, the error message you get doesn't really help to figure out which properties are causing the issue. To get a better error message that actually tells you exactly what's wrong, you can add the following overrides to your context:

public class ApplicationDbContext : DbContext
{
    ...

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException e)
        {
            ThrowEnhancedValidationException(e);
        }

        return 0;
    }

    public override Task<int> SaveChangesAsync()
    {
        try
        {
            return base.SaveChangesAsync();
        }
        catch (DbEntityValidationException e)
        {
            ThrowEnhancedValidationException(e);
        }

        return Task.FromResult(0);
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken)
    {
        try
        {
            return base.SaveChangesAsync(cancellationToken);
        }
        catch (DbEntityValidationException e)
        {
            ThrowEnhancedValidationException(e);
        }

        return Task.FromResult(0);
    }

    protected virtual void ThrowEnhancedValidationException(DbEntityValidationException e)
    {
        var errorMessages = e.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);

        var fullErrorMessage = string.Join("; ", errorMessages);
        var exceptionMessage = string.Concat(e.Message, " The validation errors are: ", fullErrorMessage);
        throw new DbEntityValidationException(exceptionMessage, e.EntityValidationErrors);
    }
}

Now, when this exception is raised, the error you see on the yellow screen of death will tell you exactly which properties are failing and why, making it much easier to track down the source of the issue and fix it.

comments powered by Disqus