Tag Archives: The model backing the ‘XXX’ context has changed

The model backing the ‘XXX’ context has changed [Solved]

 

The model backing the ‘xxx’ context has changed error

 

When using the code first of Entity Framework, the model backing the ‘xxx’ context has changed error will appear when the structure of the model is changed, because the structure of the model is inconsistent with that of the corresponding table in the database, so it cannot be modified directly

The solutions given on the Internet are as follows:

1–> Simply delete the database (including all the data in it), and then let code first use the default rule (no database – create new database) to create the database using the update model

This is obviously very troublesome

2–> Code first has a set of initialization strategies to use when encountering model changes. This behavior deletes the database and reconstructs it. By default, it is encapsulated in a class named createdatabaseifnotexists. You can tell which strategy is used by the executing program (here it means the console program)

In this way, you still have to delete and rebuild the database, and the cost is very high

3–> Need application in global.asax_ In the start method:

Database.SetInitializer< Models.XXXXDBContext>( null);

I haven’t tried this method. It should be aimed at MVC framework

Here I give a solution, which can also be found on the Internet:

1. Open the tool — > Nuget package manager — > Package manager console

2. In PM > After that, enter enable migrations – contexttypename databasename (if the execution fails, re-enter it with reference to the failure message, and the failure message is very clear; Databasename is the name of the database you generated). Then you find that a migrations folder has been added to the project, and some code has been generated automatically. Try to generate the code according to your model and changes

3. Set the code in the configuration file under the migrations folder: automaticmigration enabled = true; That is, change false to true

4. In PM > After that, enter add migration initialcreate
as the input

5. In PM > Later, update database – verb or update database – verb – force force force changes the database

After that, every time you change the model, you only need to change the model in PM > You can enter update database – verb – force later