0

In my code I am trying to check if my entity framework Code First model and Sql Azure database are in sync by using the "mycontext.Database.CompatibleWithModel(true)". However when there is an incompatibility this line falls over with the following exception.

"The model backing the 'MyContext' 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 DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."

This seems to defeat the purpose of the check as the very check itself is falling over as a result of the incompatibility.

For various reasons I don't want to use the Database.SetInitializer approach.

Any suggestions?

Is this a particular Sql Azure problem?

Thanks Martin

AvkashChauhan
  • 20,495
  • 3
  • 34
  • 65
Martin
  • 1,001
  • 3
  • 13
  • 17
  • What is your MVC and EF version? Depend on different versions there are different way to handle such issues.. Also if you don't want to use Database.SetInitializer, you still can use Database.SetInitializer(null); in Application_Start() at Global.asax – AvkashChauhan May 30 '12 at 19:17
  • I am using MVC3 and EF v4. @AvkashChauhan – Martin May 31 '12 at 06:10

1 Answers1

0

Please check out the ScottGu blog below:

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

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);

Using above code you are no recreating the database instead using the existing one so I don't think using Database.SetInitializer is a concern unless you have some serious thoughts about using it.

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

Community
  • 1
  • 1
AvkashChauhan
  • 20,495
  • 3
  • 34
  • 65