67

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.

3
  • As long as both entities are in the same DbContext, then that shouldn't be a problem. You configure the DbContext to use a connection string, and all entities will use it.
    – AaronLS
    Feb 19, 2013 at 1:39
  • I've had this same issue, but my workaround has been to enable-migrations in the package manager console. I have no idea why this works.
    – droo46
    Jun 11, 2015 at 15:33
  • 1
    This usually happens when your context class DbContext changed to IdentityDbContext
    – PPB
    May 8, 2020 at 11:54

17 Answers 17

74

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.

6
  • 2
    This was the quickest solution for me. I had added 1 new bit column to the table and added a corresponding property to my C# model. I didn't want to drop all my data and reset everything, so I just deleted this _Migrations history table and it picked up the new column in C# just fine. Jun 15, 2016 at 19:11
  • 1
    same deal; I was worried about all the code-first migration stuff I had to do, when it clearly seemed like I didn't. deleting the _MigrationsHistory table cleared everything up for me too! Oct 19, 2016 at 5:09
  • 2
    Solved my problem. Thanks
    – Sunil
    Jul 24, 2017 at 8:48
  • what is that table for anyway? why do we need to have it?
    – Emil
    Dec 25, 2017 at 16:27
  • 1
    Deleting _MigrationsHistory table in the database worked Jan 22, 2021 at 5:51
52

EF codefirst will look at your DbContext, and discover all the entity collections declared in it(and also look at entities related to those entities via navigation properties). It will then look at the database you gave it a connection string to, and make sure all of the tables there match the structure of your entities in model. If they do not match, then it cannot read/write to those tables. Anytime you create a new database, or if you change something about the entity class declarations, such as adding properties or changing data types, then it will detect that the model and the database are not in sync. By default it will simply give you the above error. Usually during development what you want to happen is for the database to be recreated(wiping any data) and generated again from your new model structure.

To do that, see "RecreateDatabaseIfModelChanges Feature" in this article: http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

You basically need to provide a database initializer that inherits from DropCreateDatabaseIfModelChanges (RecreateDatabaseIfModelChanges is now deprecated). To do this, simply add this line to the Application_Start method of your Global.asax file.

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

Once you go to production and no longer want to lose data, then you'd remove this initializer and instead use Database Migrations so that you can deploy changes without losing data.

7
  • 5
    The RecreateDatabaseIfModelChanges is now DropCreateDatabaseIfModelChanges: See this post. May 5, 2015 at 19:29
  • 1
    I am working with a database that has been around for years and many other systems depend on that database, so no chance that I can change anything at all on that database. Actually I have never in my 13 years of professional development worked on a project where we can just change the database because som code changed. How will I fix that exact same error? Aug 3, 2017 at 12:01
  • @AxelAndersen If you have source control check changes for the changeset and identify what Entity changed, then rollback that entity. You can also use "EF migrations" to generate a SQL changescript to help you understand what it is trying to change to help you identify what EF entity has gotten out of sync. If you don't want to change the DB, then you cannot change the EF entity classes.
    – AaronLS
    Aug 3, 2017 at 13:47
  • @AaronLS I have actually not changed anything existing, I am trying to manually create a new class matching a DB table. Should that not be possible? Aug 4, 2017 at 17:36
  • 1
    @AxelAndersen I suggested that you use EF migrations to generate a change script to determine what changes EF is attempting to make. Even though you tested with a single table, once you have the new table in the existing project then there are potential implied relationships/FKs that EF is detecting as needing to be deployed that your DB doesn't have. There's no point in trying to guess. You have a tool at your disposal to reveal what the differences are. Then post a new question with EF models and resulting change script if you need help modifying the model to eliminate differences.
    – AaronLS
    Aug 7, 2017 at 13:41
41

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

Database.SetInitializer<MyDbContext>(null);
7
  • 28
    Is this solving the problem or just hiding the symptoms?
    – John S
    Mar 26, 2015 at 20:04
  • 1
    Maybe it prevents the ERM from touching the database (sometimes that's what we want). Not sure what is done exactly.
    – Ernesto
    Jul 14, 2017 at 19:19
  • 2
    This answer is particularly useful when calling the stored proc using context.Entities.SqlQuery(""). May 21, 2018 at 13:00
  • Genious! Thank you!
    – Vladislav
    Feb 26, 2021 at 16:07
  • This actually helps when I am using an existing table and I don't want to use all the fields in my model.
    – Phil
    Apr 27, 2021 at 18:56
14

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

8

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

1
  • Thank you. This is really helpful. Oct 29, 2021 at 18:58
4

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

4

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

0
3

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.

2

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>
2

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/

1

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.

0
1

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
1

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

0

If you use identity, Maybe your context name is different than migrationHistory last record context Key. So you need to make a name change in this part of your code with new name in ContextKey:

         Database.SetInitializer<ContextName>(null);
0

I had this error and it turn out that I have added couple of properties to a model which I wasn't ready to migrate

Simply comment the additional properties or migrate them to database

There is no need to drop and recreate database.

1
0

I forgot to rebuild the solution and copy/paste the files.

When you're running the application locally and hosting it in IIS, for instance in C:\inetpub\WebApplication1.

Rebuild your WebApplication1 and copy/paste the files from YourSolution/WebApplication1/bin/app.publish to C:\inetpub\WebApplication1.

0
This will work : 

add this in ProjectContext.cs file 

 **Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProjectContextName>()); // to sync table structure and model class**

I have done like this : (QuizzContext.cs)

public class QuizzContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Question> Questions { get; set; }

    public QuizzContext() : base("QuizzConnection")
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<QuizzContext>()); // to sync table structure and model class
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.