I am getting this error when trying to work on Code First migration with Entity Framework
The model backing the 'bwavenueDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
here is the error image
How can I resolve it?why is it throwing the error?
You may have done database changes in the database, 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.
You need to run command of Add-Migration
and Update-database
, in the Nuget package manager console.
Or 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.
Or in Application_Start() Method in Global.asax.cs file
Database.SetInitializer<MyDbContext>(null);
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly