Code First Migrations更新資料庫結構(資料移轉)

來源:互聯網
上載者:User
背景

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

要求

  1. 已安裝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:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.