Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I created a "Code Only" POCO for use against an existing database using Entity Framework 4 and the CTP4. When I run a query I get the error

The model backing the 'xyzContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

I'm unclear on why this is happening or what I can change. I merely created the POCO, defined a simple DbContext, made a few tweaks, and then tried to run a simple query. Since I'm using "Code Only", I'm unaware of any configuration settings that need to be made. And I certainly don't want to recreate or delete the database since it's an existing database.

Thanks for any ideas.

like image 928
Donald Hughes Avatar asked Aug 23 '10 21:08

Donald Hughes


2 Answers

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); 
like image 147
Donald Hughes Avatar answered Sep 20 '22 10:09

Donald Hughes


This is a bug in CTP4 for using EF with pre-existing databases.

You can fix it by calling:

Database.SetInitializer<YourContext>(null); 

in the Application_Start method of Global.asax

like image 34
Steve Lydford Avatar answered Sep 22 '22 10:09

Steve Lydford