Entity Framework Code Only error: the model backing the context has changed since the database was created

I found the answer in the comments on this post on Scott Guthrie’s blog.

http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx

For those who are seeing this exception:

“The model backing the ‘Production’ context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance.”

Here is what is going on and what to do about it:

When a model is first created, we run a DatabaseInitializer to do things like create the database if it’s not there or add seed data. The default DatabaseInitializer tries to compare the database schema needed to use the model with a hash of the schema stored in an EdmMetadata table that is created with a database (when Code First is the one creating the database). Existing databases won’t have the EdmMetadata table and so won’t have the hash…and the implementation today will throw if that table is missing. We’ll work on changing this behavior before we ship the fial version since it is the default. Until then, existing databases do not generally need any database initializer so it can be turned off for your context type by calling:

Database.SetInitializer<Production>(null);

Leave a Comment