code first起初當修改model后,要持久化至數據庫中時,總要把原數據庫給刪除掉再創建(DropCreateDatabaseIfModelChanges),此時就會產生一個問題,當我們的舊數據庫中包含一些測試數據時,當持久化更新后,原數據將全部丟失,故我們可以引入EF的數據遷移功能來完成。
- 已安裝NuGet
注:區別在於,我們給teacherName屬性加了一個長度限制。
接下來,我們將開始持久化此model至數據庫中(我們現在只是對屬性作修改,此時數據庫中此字段的長度為nvarchar(max),並不是nvarchar(10))
1:在config中配置數據庫連接:
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,將作出如下修改:
再次執行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
數據庫中的原數據也沒有丟失!