O'Reilly logo

Programming Entity Framework: Code First by Rowan Miller, Julia Lerman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding How Model Changes Impact Database Initialization

If you were to run the console application again, you’d get a big fat InvalidOperationException. There’s nothing wrong with the model changes that we’ve made here. The problem is with the default behavior of Code First database initialization. So we’re going to have to stop the presses, switch gears, and fix this problem before moving on with exploring configuration.

Here’s the exact exception message:

The model backing the ‘BreakAwayContext’ 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.

By default, Code First will create the database only if it doesn’t already exist, but your database does exist.

Remember that EdmMetadata table in the database? If not, take a peek at Figure 2-1 again. That table contains a snapshot of the database section of the model that Code First built. When Code First uses a model for the first time in an application process, by default, it will go through its model building process. Then it will compare the in-memory model with the last version—which it can see by reading the EdmMetadata table. In this case, Code First recognized that the metadata of the new model does not match the metadata of the previous model and therefore cannot ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required