当前位置: 代码迷 >> ASP.NET >> EF Code First,entity framework.数据表发生改变后如何避免
  详细解决方案

EF Code First,entity framework.数据表发生改变后如何避免

热度:3310   发布时间:2013-02-25 00:00:00.0
EF Code First,entity framework.数据表发生改变后如何处理
如题,最近在看MVC 3,按照官方的教程自己动手加深理解:http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part7-cs
在这一节中,遇到麻烦,就是当数据库表添加字段后,尽管我改了Model,还是报错:
The model backing the 'MovieDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data. 

按照教程,应对这种问题,有2个方案:
There are two approaches to resolving the error:

Have the Entity Framework automatically drop and re-create the database based on the new model class schema. This approach is very convenient when doing active development on a test database, because it allows you to quickly evolve the model and database schema together. The downside, though, is that you lose existing data in the database — so you don't want to use this approach on a production database! 

Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of this approach is that you keep your data. You can make this change either manually or by creating a database change script. 
第一个其实就是删除原有的DB,重新新建一个。
第二个方法是修改model,让其和DB保持结构上的统一。我去尝试了,但是运行后依然报相同的错,就是我贴出来的错误描述。

不知道有人成功解决过此问题吗?



------解决方案--------------------------------------------------------
属性和数据库对应 删除数据库里多余的一张表

要先删除数据库中dbo.EdmMetadata这张表。
比如我现在往Category类中加一个Status字段
public string Status { get; set; }

然后往数据库的Categories表中也添加Stauts这个字段,这样程序还是能照常运行的,不会清空数据库原有内容。
  相关解决方案