1. 程式人生 > >Code First Migrations更新數據庫結構(數據遷移)

Code First Migrations更新數據庫結構(數據遷移)

ply 示例 文件夾 就會 class .com loss ati user

背景

code first起初當修改model後,要持久化至數據庫中時,總要把原數據庫給刪除掉再創建(DropCreateDatabaseIfModelChanges),此時就會產生一個問題,當我們的舊數據庫中包含一些測試數據時,當持久化更新後,原數據將全部丟失,故我們可以引入EF的數據遷移功能來完成。

要求

  1. 已安裝NuGet

過程示例 [csharp] view plain copy
  1. //原model
[csharp] view plain copy
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. public class Lesson {
  5. public int lessonID { get; set; }
  6. [Required]
  7. [MaxLength(50)]
  8. public string lessonName { get; set; }
  9. [Required]
  10. public string teacherName { get; set; }
  11. public virtual UserInfo UserInfo{get;set;}
  12. }
[csharp] view plain copy
  1. //新model
[csharp] view plain copy
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. public class Lesson {
  5. public int lessonID { get; set; }
  6. [Required]
  7. [MaxLength(50)]
  8. public string lessonName { get; set; }
  9. [Required]
  10. [MaxLength(10)]
  11. public string teacherName { get; set; }
  12. public virtual UserInfo UserInfo{get;set;}
  13. }

註:區別在於,我們給teacherName屬性加了一個長度限制。

接下來,我們將開始持久化此model至數據庫中(我們現在只是對屬性作修改,此時數據庫中此字段的長度為nvarchar(max),並不是nvarchar(10))

1:在config中配置數據庫連接:

[html] view plain copy
  1. <connectionStrings>
  2. <add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PC\SQLEXPRESS" providerName="System.Data.SqlClient" />
  3. </connectionStrings>

2:打開NuGet控制臺:

技術分享

3:運行命令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.

此時項目會出現如下文件夾:

技術分享

打開configuation.cs,將作出如下修改:

[csharp] view plain copy
  1. public Configuration()
  2. {
  3. AutomaticMigrationsEnabled = true;
  4. }


再次執行Update-Database:

因為我把長度從max改為10,在更新數據結構時,它認為此操作會導致數據丟失,如下:

Specify the ‘-Verbose‘ flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Applying automatic migration: 201212090848057_AutomaticMigration.
Automatic migration was not applied because it would result in data loss.

如果確保沒事,只需給此命令加個強制執行的參數即可:

Enable-Migrations -Force

最後再次執行:Update-Database

技術分享

數據庫中的原數據也沒有丟失!

Code First Migrations更新數據庫結構(數據遷移)