Entity Framework Code First and Connection Strings

I have a small MVC 3 application using Entity Framework Code First and use this connection string for the model:

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Journal.mdf;User Instance=true;Database=MyJournal 

When I make changes to the model (for example, add a property), I get as expected

The model supporting the JournalContext context has changed since the database was created.

So, while in development mode, I continue and delete Journal.mdf and Journal.ldf.

Now, when I launch the application again, I get

Unable to open the database "MyJournal" requested at login. Login failed.

If I change the connection string to

 data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Journal.mdf;User Instance=true;Database=MyJournal2 

(changed the parameter Database= by adding "2")

The .mdf magazine is created and the application works again. If I make a series of changes and try to “rework” any database name again, I get a “Can't open” message.

Why do I need to provide a unique database name every time I change the model, and how can I “clear” previous names?

+6
source share
1 answer

Each unique database name is not required. When the model is first created, it launches the DatabaseInitializer to do things like create a database if it is not there or add seed data. By default, DatabaseInitializer tries to compare the database schema needed to use the model with the hash of the schema stored in the EdmMetadata table created using the database (when Code First is the one that creates the database). If the hash comparison is different, it causes this error.

Obviously, if you change the connection string, then it will create a completely new database called MyJournal2.

To work around this, you need to delete the EdmMetadata table and start the initializer again. You can do this by going to the Database Explorer window in Visual Studio and connecting to your database, then go to Tables, where you should find the EdmMetadata table by right-clicking on it and choosing Delete.

Alternatively put

 DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<dbType>()); 

in your Application_Start method in Global.asax.cs. This will delete the database and recreate it whenever the schema changes.

See this video for multiple comparisons for more information , especially when the classes change .

Also check out this link for DropCreateDatabaseIfModelChanges . He tells you what is really happening and how to seed the database, if you need, by creating a derived class.

+6
source

Source: https://habr.com/ru/post/902259/


All Articles