型号来头DB语境已经改变;考虑code首先迁移 [英] Model backing a DB Context has changed; Consider Code First Migrations

查看:82
本文介绍了型号来头DB语境已经改变;考虑code首先迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该模式支持了MyDbContext'环境已经改变,因为该数据库已创建。考虑使用code首先迁移到更新数据库(<一个href=\"http://go.microsoft.com/fwlink/?LinkId=238269\">http://go.microsoft.com/fwlink/?LinkId=238269).

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.

修改

它是与我试图用两个独立的实体共享一个连接字符串(即数据库)的事实。

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 codefirst会看你的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.

要做到这一点,请参阅RecreateDatabaseIfModelChanges功能这篇文章在:
<一href=\"http://weblogs.asp.net/scottgu/archive/2010/07/16/$c$c-first-development-with-entity-framework-4.aspx\">http://weblogs.asp.net/scottgu/archive/2010/07/16/$c$c-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

您基本上需要提供从RecreateDatabaseIfModelChanges继承的数据库初始化。

You basically need to provide a database initializer that inherits from RecreateDatabaseIfModelChanges.

在你去生产,不再想丢失数据,那么你会删除此初始化,而使用的数据库迁移,使您可以部署,而不会丢失数据的变化。

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语境已经改变;考虑code首先迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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