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

Viewed 46637

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.

7 Answers

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

I had the same issue - re-adding the migration and updating the database didn't work and none of the answers above seemed right. Then inspiration hit me - I'm using multiple tiers (one web, one data, and one business). The web layer never threw this exception - it was the business layer (which I set as console application for testing and debugging). Turns out the business layer wasn't using the right connection string to get the db and make the context. So I added the connection string to the app config and viola it works. Putting this here for others who may encounter the same issue.

This was resolved for me by adding this to by context constructor.

Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());

After doing this my code-first migrations now run automatically when the db already exists.

For this Error in my case, i just deleted all records on "_MigrationHistory" Table, from "DBControlContext". I hope this is helpful.

Related