[asp.net-mvc] Model backing a DB Context has changed; Consider Code First Migrations

The model backing the 'MyDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

What causes this to happen? I've literally just created a brand new database and have changed nothing, but every time I try to access a model from a controller it throws this.

Edit

It has something to do with the fact that I was attempting to share a connection string (i.e. a database) with two separate entities.

This question is related to asp.net-mvc entity-framework

The answer is


If you have changed the model and database with tables that already exist, and you receive the error "Model backing a DB Context has changed; Consider Code First Migrations" you should:

  • Delete the files under "Migration" folder in your project
  • Open Package Manager console and run pm>update-database -Verbose

To solve this error write the the following code in Application_Start() Method in Global.asax.cs file

Database.SetInitializer<MyDbContext>(null);

In case you did changes to your context and you want to manually make relevant changes to DB (or leave it as is), there is a fast and dirty way.

Go to DB, and delete everything from "_MigrationHistory" table


This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges feature (formerly known as 'RecreateDatabaseIfModelChanges' feature) by adding the following code in your Global.asax.cs:

Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());

Run your application again.

As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.


Entity Framework detects something about the model has changed, you need to do something to the database to get this work. Solution: 1. enable-migrations 2. update-database


Adding this as another possible solution, because this is what fixed it in our case;

Make sure if you have multiple projects that they are using the same Entity Framework Nuget package version!.

In our case we had one project ( call if project A ) holding the EF code first context with all entities. It was this project that we were using to add migrations & update the database. However a second project ( B ) was referencing project A to make use of the context. When running this project we got the same error;

The model backing the 'MyDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).


You can fix the issue by deleting the __MigrationHistory table which is created automatically in the database and logs any update in the database using code-first migrations. Here, in this case, you manually changed your database while EF assumed you had to do it with the migration tool. Deleting the table means to the EF that there are no updates and no need to do code-first migrations thus it works perfectly fine.


Easiest and Safest Method If you know that you really want to change/update your data structure so that the database can sync with your DBContext, The safest way is to:

  1. Open up your Package Manager Console
  2. Type: update-database -verbose -force

This tells EF to make changes to your database so that it matches your DBContext data structure


In my case this error was caused by the existence of the _MigrationsHistory table in the database. Deleting that table fixed the problem. Not sure how that table got into our test environment database.


This error occurs when you have database is not in sync with your model and vice versa. To overcome this , follow the below steps -

a) Add a migration file using add-migration <{Migration File Name}> through the nuget package manager console. This migration file will have the script to sync anything not in sync between Db and code.

b) Update the database using update-database command. This will update the database with the latest changes in your model.

If this does not help, try these steps after adding the line of code in the Application_Start method of Global.asax.cs file -

Database.SetInitializer<VidlyDbContext>(new DropCreateDatabaseIfModelChanges<VidlyDbContext>());

Reference - http://robertgreiner.com/2012/05/unable-to-update-database-to-match-the-current-model-pending-changes/


Just go to Package Manage Console, type the following:

Enable-Migrations

*If the error like this appears "Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration."

Do this >>> Add-Migration

*Visual studio will ask for a name, kindly input the name you want.

Update-Database


You need to believe me. I got this error for the simple reason that I forgot to add the connection string in the App.Config(mine is a wpf project) of your startup project.

The entire config in my case

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="ZzaDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ZaaDbInDepth;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>