模型支持DB上下文已更改;考虑代码优先迁移 [英] Model backing a DB Context has changed; Consider Code First Migrations

查看:621
本文介绍了模型支持DB上下文已更改;考虑代码优先迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


自创建数据库以来,支持MyDbContext上下文的模型已更改。考虑使用代码优先迁移来更新数据库( 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.

修改

这与我正在尝试的事实有关共享连接字符串(即一个数据库)与两个独立的实体。

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.

推荐答案

EF代码首先将看看你的DbContext,并发现在其中声明的所有实体集合(以及通过导航属性查看与这些实体相关的实体)。然后,它会查看您给它一个连接字符串的数据库,并确保所有表格与模型中实体的结构相匹配。如果它们不匹配,那么它不能读/写这些表。无论何时创建新数据库,或者如果您更改了实体类声明,例如添加属性或更改数据类型,则会检测到模型和数据库不同步。默认情况下,它将简单地给你上面的错误。通常在开发过程中,您想要发生的是数据库被重新创建(擦除任何数据)并再次从您的新模型结构生成。

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.

为此,请参阅在本文中,重新创建数据库IfModelChanges功能
http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

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

您基本上需要提供从DropCreateDatabaseIfModelChanges继承的数据库初始化程序(现在已不再使用RecreateDatabaseIfModelChanges)。为此,只需将此行添加到 Global.asax 文件的 Application_Start 方法中。

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.

这篇关于模型支持DB上下文已更改;考虑代码优先迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆