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 (ie a database) with two separate entities.
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.
要解决此错误,请在Global.asax.cs文件的Application_Start()方法中编写以下代码
Database.SetInitializer<MyDbContext>(null);
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.
链接地址: http://www.djcxy.com/p/49688.html上一篇: EF6 1:可选+ 1:很多