25

I've got this error for the 762nd time but this time I am getting it as soon as I attempt to access my Production site, straight after deleting the 'production' database on Azure and then publishing my site.

The model backing the 'PropertyContext' context has changed since the database was created. Consider using Code First Migrations to update the database

I deleted the database because I couldn't fix this issue any other way but it still doesn't work.

Some important points:

  • I'm using EF6 and publishing to Azure.
  • This is 1 of 2 projects/sites that uses the same Repo project. I have no
    problems with the other one, just this one.
  • I have tried publishing the problem project first (after deleting the db) and second with the same result.
  • I have tried deleting both WEBSITES and the DB from Azure and starting again
  • I have tried deleting all migrations and starting with a fresh data model
  • I have tried the following in my Global.asax (in both projects)

    Database.SetInitializer PropertyContext>(null); <-- SO won't let me put the first <

and

Database.SetInitializer(new MigrateDatabaseToLatestVersion<PropertyContext, MyConfiguration>());
new PropertyContext().Database.Initialize(true);

I'm using .net 4.5

Why am I getting this error on a new database and how can I get this site to work?

Stuart Dobson
  • 3,001
  • 4
  • 35
  • 37
  • Here's a link showing how to fix this: http://www.dotnetcurry.com/showarticle.aspx?ID=820 – Thiago Custodio Feb 18 '14 at 13:56
  • Doesn't work as many of the commands generated don't work on Azure – Stuart Dobson Feb 19 '14 at 08:04
  • Hey Stuart, no answer marked. Could you provide some more info if your are still having problems? – Talon Jul 14 '14 at 13:21
  • As stated on Ohlin's answer, I ended up deleting all sites and databases from the server, deleted all migrations, then deploying again. So essentially there is no answer to this. – Stuart Dobson Jul 15 '14 at 22:41
  • I had the same problem.. resolved by using First Answer of [This Question][1] [1]: http://stackoverflow.com/questions/13238203/automatic-migrations-for-asp-net-simplemembershipprovider – Muhammad Nasir Shamshad Oct 21 '14 at 05:45
  • http://stackoverflow.com/questions/3600175/the-model-backing-the-database-context-has-changed-since-the-database-was-crea/37950882#37950882 – Shafqat Jun 21 '16 at 17:30

6 Answers6

37

Just ran into the same error in ASP.Net application. In my case I did not use Code First, but I used standard ASP.Net authentication provider which apparently uses Code First, and authentication was broken because of this issue.

Here is quick and dirty solution is you don't care much about existing user records:

For me the solution was to drop the dbo.__MigrationHistory table, authentication started working fine after that. Be aware! This solution is not for everyone! This will fix the problem, but it is potentially risky.

If you cannot afford to lose data in AspNet* tables:

ASP.Net authentication provider automatically creates tables in your database:

  • AspNetRoles
  • AspNetUsers
  • AspNetUserRoles
  • AspNetUserClaims
  • AspNetUserLogings

The tables are empty by default, if you haven't created any new logins for your web site, you can use "quick and dirty" solution above. If you do care about preserving user information or just curios how Code First migrations work, follow these steps:

  • Open your Web.config file and check the name of the connection string you have for your database. It will be one of the records under <connectionStrings> element.
  • Open Package Manager Console:

    Tools –> Library Package Manager –> Package Manager Console

  • In Package Manager Console window, use a drop-down to set Default Project. Make sure this is the project that contains ASP.Net authentication provider code.
  • Execute command:
    Update-Database -ConnectionStringName MyConnectionStringName

Replace the MyConnectionStringName with the actual name you looked up in web.config.

As a result of this command you will see a new folder "Migrations" with a bunch of code generated by the Update-Database command. Re-build and re-deploy your app, your new migration code will be executed on startup and would bring the database schema in sync with an updated version of ASP.Net authentication provider code.

seva titov
  • 11,720
  • 2
  • 35
  • 54
  • 2
    Thanks you so much , i wasted a lot of time on this stupid issue , then i resolved it by deleting this stupid dbo.__MigrationHistory table thanks again my friend – Muhammad Al-Own May 31 '15 at 12:54
  • 2
    You, sir, are a hero today. – alex.davis.dev Nov 18 '15 at 01:45
  • Yes, it worked. I think this happens because there exists the code first migration class in the new .dll but the corresponding record is missing from the __MigrationHistory table. Another fix could be to run the data comparison on the __MigrationHistory but there is not much point in doing that. – Paceman Dec 17 '15 at 15:02
  • Although this will fix the problem it is not a good solution. Deleting the __migrationhistory table you are removing the ability for codefirst to track your database changes. You will no longer be able to use update-database. The error is clear, it says "You have made changes to your database entities in code but you have not updated the database to reflect these changes." See my answer for a detailed step-by-step guide on how to simply update the database from your visual studio. – Talon Jan 15 '16 at 14:56
  • If you don't care about your data, you can just initialize your DbContext with a [`DropCreateDatabaseIfModelChanges` initializer](http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx) – xr280xr Sep 28 '17 at 20:16
27

When using Code First with Migrations, your database creates a table called __MigrationHistory to track the current schema. When you run your application your Entity Framework will check this table to make sure that the database schema matches your database entities. If they do not match, you will get this error.

To update your database follow these steps:

  1. Open the Package Manager Console (View -> Other Windows -> Package Manager Console) in Visual Studio
  2. In the Package Manager Console Window, there is a drop down with your projects in, make sure it is set to the project that contains your DbContext
  3. Make sure that the project that contains your App.Config / Web.Config file is "Set as Startup Project" (If you have multiple Configs, it must be the one with the Database Connection String defined.
  4. Type Update-Database -ConnectionStringName MyConnString where MyConnString is the name (not the actual connection string) of your connection string in your App.Config / Web.Config

If you get an error like this: "Unable to update database to match the current model because there are pending changes and automatic migration is disabled."

You should enable Automatic Migrations and try again. To enable Automatic Migrations

  1. In the Migrations folder (in the project with your DbContext), open Configuration.cs.
  2. Make sure the Constructor contains: AutomaticMigrationsEnabled = true;

To stop Entity Framework/DbContext from monitoring changes on your database you could simply delete the __MigrationHistory table in your database. It is then up to you to make sure that the database remains updated manually.

MSDN article here

SharpC
  • 6,974
  • 4
  • 45
  • 40
Talon
  • 3,466
  • 3
  • 32
  • 47
  • Funny I got this error following a MVA video but they didn't show how to fix it. This worked for me though. – ChrisPBacon Feb 05 '16 at 22:05
  • 1
    Also make sure the Package Manage Console window is wide enough. If it's too narrow the Default project drop down does not display! – SharpC Apr 29 '16 at 10:14
  • I find this to be a very odd procedure. One, that you use Package Manager to do it. When I think of Package Manager I think of Nuget packages. What does this have to do with packages? Two, do you need to build the project first or does it do that itself? – xr280xr Sep 28 '17 at 20:23
  • 1
    @xr280xr Microsoft have never been the experts at naming things right. "Visual Studio" should be a graphics program! Moving on, the package manager is actually a Visual Studio powershell console. You can even execute git, npm, grunt, etc... commands there too. The project must be able to compile, I normally build my app just out of habit to make sure everything is working. – Talon Sep 29 '17 at 20:41
7

The solution from this is to use the static method SetInitializer and bind to the context a Null value. If you are working on a Web solution, the best position to write the code is in the Application_Start of your Global.asax.cs file.

protected void Application_Start() 
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    //...
    Database.SetInitializer<MyContext>(null);
}
Mhadonis
  • 330
  • 3
  • 11
3

I got a similar problem this morning. Suddenly the error appeared and couldn't be resolved:

The model backing the 'ApplicationDbContext' context has changed since 
the database was created. Consider using Code First Migrations to update 
the database

I have one project for MVC and another project for the model, context and repositories. I've been working on it for weeks but today it said stop.

I have tried to delete database, enable-migration, add-migration and update-database so many times that I've lost count. I've added initializers to MigrateDatabaseToLatestVersion as well as DropCreateDatabaseIfModelChanges. All in vain...

What finally made it work was to move model, context and repositories into the MVC project (not something I was keen on)...then it worked right out of the box without any code changes at all (besides namespaces)! Very strange...

I've read so many blog posts during the day trying to solve this problem. One of them (I don't know which one) mentioned a bug in Visual Studio 2013 where reference to DLL files weren't always updated as they should, suggesting that my MVC project missed out something when I was running add-migration and update-database in my separate project. But it's just a guess.

I'm using EF 6.1 and .Net 4.5.1 in my solution.

Ohlin
  • 4,068
  • 2
  • 29
  • 35
  • Thanks for the response. Horrible solution but this may come in handy some time. I ended up deleting all sites and databases from the server, deleted all migrations, then deploying again. Lucky it's not my real "Production" server.. – Stuart Dobson Feb 20 '14 at 22:31
  • Yes, that's the scary scenario - what do you do if it's a production server? I just hope I'll never reach there. I'm glad you solved it :) – Ohlin Feb 21 '14 at 06:43
  • did you filed a bug for this ? I'm running into the same issue, just updated to last beta version but same thing is happening, i've reverted the last changes and same thing. – L.Trabacchin Mar 19 '14 at 12:02
  • No, I didn't file a bug for this since I managed to find a work around. Should have done it, but didn't... – Ohlin Mar 19 '14 at 12:21
1

Got a similar problem! Answer is here http://www.asp.net/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-a-new-field

(Rick Anderson) There are two approaches to resolving the error:

  1. Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient when doing active development on a test database, because it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don't want to use this approach on a production database!

  2. Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script.

saka saka
  • 11
  • 2
0

I have spent some hours trying to solve this problem. One project was working, the other one wasn't.

I had different projects referencing different versions of Entity Framework. In my case, I had a Console app and a Windows Service app, both referencing a third project containing code first classes and DbContext.

After running Update-Package EntityFramework everything worked fine in both projects.

Alisson Reinaldo Silva
  • 10,009
  • 5
  • 65
  • 83