Pages

Tuesday, May 6, 2014

Migration: Helpful When Seeding Database and Error is Thrown

Using Entity Framework Migration, I was seeding a database.

From the Package Manager Console window and after entering Update-Database, an error was displayed.

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

This was the only information about error, and the error message didn’t indicate any good advise what caused the error.

Shown below is a work-around found at StackOverflow, which helped pin point the error.

Stackoverflow Overridding SaveChanges

public partial class Database : DbContext
{
public override int SaveChanges()
{
try
{
return base.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
); // Add the original exception as the innerException
}
}
}



This post is for the purpose of my notes only.
“I invented nothing new. I simply assembled the discoveries of other men behind whom were centuries of work. Had I worked fifty or ten or even five years before, I would have failed. So it is with every new thing. Progress happens when all the factors that make for it are ready and then it is inevitable. To teach that a comparatively few men are responsible for the greatest forward steps of mankind is the worst sort of nonsense.”



Henry Ford

No comments:

Post a Comment