Reputation: 10163
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.
Upvotes: 69
Views: 207421
Reputation: 1
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
}
}
Upvotes: 0
Reputation: 187
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.
Upvotes: 0
Reputation: 21
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.
Upvotes: 0
Reputation: 568
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);
Upvotes: 0
Reputation: 104
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.
Upvotes: 3
Reputation: 115
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
Upvotes: 4
Reputation: 423
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).
Upvotes: 4
Reputation: 583
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/
Upvotes: 2
Reputation: 25553
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>
Upvotes: 2
Reputation: 38394
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.
Upvotes: 52
Reputation: 772
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
Upvotes: 1
Reputation: 1431
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:
This tells EF to make changes to your database so that it matches your DBContext data structure
Upvotes: 8
Reputation: 4237
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
Upvotes: 15
Reputation: 1802
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.
Upvotes: 77
Reputation: 11
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:
pm>update-database -Verbose
Upvotes: 1
Reputation: 1836
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.
Upvotes: 1
Reputation: 871
To solve this error write the the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer<MyDbContext>(null);
Upvotes: 41