日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql migrations_Code First Migrations更新数据库结构(数据迁移)

發布時間:2025/3/8 数据库 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql migrations_Code First Migrations更新数据库结构(数据迁移) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

背景

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

要求

已安裝NuGet

過程示例

//原modelusing 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;}

}//新modelusing 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中配置數據庫連接:

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:

本文原創發布php中文網,轉載請注明出處,感謝您的尊重!

總結

以上是生活随笔為你收集整理的mysql migrations_Code First Migrations更新数据库结构(数据迁移)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。