背景
code first起初當修改model後,要持久化至資料庫中時,總要把原資料庫給刪除掉再建立(DropCreateDatabaseIfModelChanges),此時就會產生一個問題,當我們的舊資料庫中包含一些測試資料時,當持久化更新後,原資料將全部丟失,故我們可以引入EF的資料移轉功能來完成。
要求
- 已安裝NuGet
過程樣本
//原model
using System.Collections;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;public class Lesson { public int lessonID { get; set; } [Required] [MaxLength(50)] public string lessonName { get; set; } [Required] public string teacherName { get; set; } public virtual UserInfo UserInfo{get;set;}}
//新model
using System.Collections;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;public class Lesson { public int lessonID { get; set; } [Required] [MaxLength(50)] public string lessonName { get; set; } [Required] [MaxLength(10)] public string teacherName { get; set; } public virtual UserInfo UserInfo{get;set;}}
註:區別在於,我們給teacherName屬性加了一個長度限制。
接下來,我們將開始持久化此model至資料庫中(我們現在只是對屬性作修改,此時資料庫中此欄位的長度為nvarchar(max),並不是nvarchar(10))
1:在config中設定資料庫串連:
<connectionStrings> <add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PC\SQLEXPRESS" providerName="System.Data.SqlClient" /> </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,將作出如下修改:
public Configuration() { AutomaticMigrationsEnabled = true; }
再次執行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
資料庫中的原資料也沒有丟失!
3: