使用Code first 进行更新数据库结构(数据迁移)

   CodeFirst 背景

     code first起初当修改model后,要持久化至数据库中时,总要把原数据库给删除掉再创建(DropCreateDatabaseIfModelChanges),此时就会产生一个问题,当我们的旧数据库中包含一些测试数据时,当持久化更新后,原数据将全部丢失,故我们可以引入EF的数据迁移功能来完成。 

做法:

   采用CodeFirst模式开发过程中,EntityFramework会在我们第一次运行网站的时候自动创建数据库,并生成对应的表。但是在项目的过程中,那么我们可能需要修改Model类,那么在重新运行项目的时候,就会报错了

The model backing the 'EF DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database

意思是说,数据上下文变动,在CodeFirst模式下与数据库不一致,需要更新数据库。

那么解决办法是什么呢?有的人会删除数据库,这样就会生成一个新的数据库,但是我们每次都要删除数据库吗?那么以前的数据同样都没有了,这样又要重新录入了吗?这样的做法是蛋疼的。 

   所以使用数据迁移就可以解决这个问题了 :

  打开NuGet控制台:

2.运行命令:Enable-Migrations

可能会出现例如这样的错误:

Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201212090821166_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project MvcApplication1.

此时项目会出现如下文件夹:

然后打开Configurations.cs

修改成如下:

执行:Update-Database:

可能会出现一些错误提示,没关系。继续走下去

执行:Enable-Migrations-Force

最后执行:Update-Database

你会发现数据库的数据没有改变,而数据库却更新了。

这只是我的个人工作笔记而已,希望能帮助到需要帮助的朋友,如果有什么错误的,恳请各位大神提出,小弟十分感谢!

原文地址:https://www.cnblogs.com/MrLee/p/3373228.html