Last Updated: February 25, 2016
·
5.577K
· blaiseliu

Debug into Entity Framework Code First

In the beginning, we might think it is not possible to debug our model configuration and seeding method in code first, since those codes cannot be running by clicking the debug button in Visual Studio.

Although the Package Manager Console command update-database DOES spit out some Exception info, it is difficult to dig into inner exceptions. For example,

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Here is how we can get more we need.

Inside the Seed method of the Configuration class, instead of calling context.SaveChanges(), we call a method SaveChanges(context) that wrap context.SaveChanges() inside a try:

private static void SaveChanges(DbContext context)
{
    try
    {
        context.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        var sb = new StringBuilder();
        foreach (var failure in ex.EntityValidationErrors)
        {
            sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
            foreach (var error in failure.ValidationErrors)
            {
                sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                sb.AppendLine();
            }
        }
        throw new DbEntityValidationException(
            "Entity Validation Failed - errors follow:\n" +
            sb.ToString(), ex
        ); 
    }
}

Run update-database this time, we can see all the inner exceptions:

The field XXX must be a string or array type with a maximum length of '25'.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip