Setting up Code First Migrations for Model Changes--為模型更改做數據庫遷移。
1.打開資源管理器,在App_Data文件夾下,找到movies.mdf數據庫文件,如果沒有看到點擊顯示所有文件。
2.刪掉movies.mdf數據庫文件,并編譯項目。確保沒有報錯。
3.找到工具菜單欄下面的NuGet程序包管理器---程序包管理器控制臺,如圖所示:
4,在程序包管理器控制臺中,輸入:Enable-Migrations -ContextTypeName MvcMovie.Models.MovieDBContext
(注意:MvcMovie.Models.MovieDBContext 項目名.Models.項目數據上下文)
按enter鍵之后,可以看到:
5,數據庫遷移之后,VS中自動為我們生成了一個Migrations文件夾,里面有一個Configuration.cs文件
6.打開Configuration.cs文件,引用命名空間:
using MvcMovie.Models;
然后在Seed方法中寫上:
1 PRotected override void Seed(MvcMovie.Models.MovieDBContext context) 2 { 3 context.Movies.AddOrUpdate( i => i.Title, 4 new Movie 5 { 6 Title = "When Harry Met Sally", 7 ReleaseDate = DateTime.Parse("1989-1-11"), 8 Genre = "Romantic Comedy", 9 Price = 7.99M10 },11 12 new Movie13 {14 Title = "Ghostbusters ",15 ReleaseDate = DateTime.Parse("1984-3-13"),16 Genre = "Comedy",17 Price = 8.99M18 },19 20 new Movie21 {22 Title = "Ghostbusters 2",23 ReleaseDate = DateTime.Parse("1986-2-23"),24 Genre = "Comedy",25 Price = 9.99M26 },27 28 new Movie29 {30 Title = "Rio Bravo",31 ReleaseDate = DateTime.Parse("1959-4-15"),32 Genre = "Western",33 Price = 3.99M34 }35 );36 37 }
7.Code First Migrations calls theSeed
method after every migration (that is, callingupdate-databasein the Package Manager Console), and this method updates rows that have already been inserted, or inserts them if they don't exist yet.
這句話的意思是:在每一次數據庫遷移的時候,這個seed方法都會被調用,這個方法更新已經插入的行數據,或者插入行,如果這個行數據不存在。
8.下面的方法起到了一個更新插入的作用:
1 context.Movies.AddOrUpdate(i => i.Title,2 new Movie3 {4 Title = "When Harry Met Sally",5 ReleaseDate = DateTime.Parse("1989-1-11"),6 Genre = "Romantic Comedy",7 Rating = "PG",8 Price = 7.99M9 }
9.*因為Seed方法,在每次數據庫遷移的時候,都會執行。你不能僅僅是插入數據,因為你將要插入的數據,將在第一次數據庫遷移結束之后,已經存在數據庫中;
*更新插入的操作可以預防錯誤,通過阻止你,插入已經存在的數據到數據庫中。但是它有個缺點:它重載了,所有你在測試項目時候改變的數據;
因為有些測試數據,你不想改變:比如,你測試的時候,改變了數據,但是你不想這個數據在數據庫更新的時候,發生改變。這個時候你可以做一個新增的操作:新增一個數據庫中不存在的數據。
10.看一下這句代碼吧:context.Movies.AddOrUpdate(i => i.Title,這第一個傳到AddOrUpdate方法的參數,指定了一個屬性,用來檢查是否已經存在相同的行數據,對于我這個項目來說,我這個Title,可以做為這個屬性,因為它在List中每次都是唯一的;This code assumes that titiles are unique. If you manually add a duplicate title, you'll get the following exception the next time you perform a migration.
Sequence contains more than one element 我們假想Title是唯一的,如果你手動添加了重復的Title,你將會在下次數據庫遷移的時候,報一個錯誤,了解更多,請參考鏈接的文章,哈哈,純人工翻譯的哦。因為博主喜歡英語,所以還是看外國人的資料學習編程了。MSDN很不錯的,For more information about theAddOrUpdatemethod, seeTake care with EF 4.3 AddOrUpdate Method..11.現在我們來編譯一下整個項目吧,如果這這里不編譯的話,后面的步驟中將會出錯誤。12.The next step is to create aDbMigration
class for the initial migration. This migration creates a new database, that's why you deleted themovie.mdffile in a previous step.這句話的意思是:我們接下來要為初始化數據庫遷移,創建一個DBMigration類,這個數據庫遷移創建一個新的數據庫,這也就是我們前面刪掉Movie.mdf文件的原因。13.在程序包管理器控制臺中輸入:add-migration Initial我們看到:
14.Code First Migrations creates another class file in theMigrationsfolder (with the name{DateStamp}_Initial.cs), and this class contains code that creates the database schema. The migration filename is pre-fixed with a timestamp to help with ordering. Examine the{DateStamp}_Initial.csfile, it contains the instructions to create theMovies
table for the Movie DB. When you update the database in the instructions below, this{DateStamp}_Initial.csfile will run and create the the DB schema. Then theSeedmethod will run to populate the DB with test data.
這段話的意思是:Code First遷移,在Migration文件下,創建了另外一個類(類的文件名稱是:時間_Initiaal.cs),并且這個類包含了創建數據庫的代碼。這個文件以時間的命名方式便于排序管理。檢查這個文件,它包含了怎么為MovieDB創建Moviess數據庫表。當你按照下面的指令(等會我在控制器管理控制臺中輸入的指定),更新數據庫的時候,這個文件會執行,并且創建數據庫,然后這個Seed方法,也將會執行,為數據庫生成測試數據。
先看看看這個文件里面的代碼是啥樣的吧:
1 namespace MvcMovie.Migrations 2 { 3 using System; 4 using System.Data.Entity.Migrations; 5 6 public partial class Initial : DbMigration 7 { 8 public override void Up() 9 {10 CreateTable(11 "dbo.Movies",12 c => new13 {14 ID = c.Int(nullable: false, identity: true),15 Title = c.String(),16 ReleaseDate = c.DateTime(nullable: false),17 Genre = c.String(),18 Price = c.Decimal(nullable: false, precision: 18, scale: 2),19 })20 .PrimaryKey(t => t.ID);21 22 }23 24 public override void Down()25 {26 DropTable("dbo.Movies");27 }28 }29 }
同樣看看我們之前的Migration里面Configuration.cs代碼吧:
1 namespace MvcMovie.Migrations 2 { 3 using MvcMovie.Models; 4 using System; 5 using System.Data.Entity; 6 using System.Data.Entity.Migrations; 7 using System.Linq; 8 9 internal sealed class Configuration : DbMigrationsConfiguration<MvcMovie.Models.MovieDBContext>10 {11 public Configuration()12 {13 AutomaticMigrationsEnabled = false;14 }15 16 protected override void Seed(MvcMovie.Models.MovieDBContext context)17 {18 context.Movies.AddOrUpdate(i => i.Title,19 new Movie20 {21 Title = "When Harry Met Sally",22 ReleaseDate = DateTime.Parse("1989-1-11"),23 Genre = "Romantic Comedy",24 Price = 7.99M25 },26 27 new Movie28 {29 Title = "Ghostbusters ",30 ReleaseDate = DateTime.Parse("1984-3-13"),31 Genre = "Comedy",32 Price = 8.99M33 },34 35 new Movie36 {37 Title = "Ghostbusters 2",38 ReleaseDate = DateTime.Parse("1986-2-23"),39 Genre = "Comedy",40 Price = 9.99M41 },42 43 new Movie44 {45 Title = "Rio Bravo",46 ReleaseDate = DateTime.Parse("1959-4-15"),47 Genre = "Western",48 Price = 3.99M49 }50 );51 }52 }53 }
現在我們在,程序包管理器控制臺中輸入這個指令來創建數據庫,并運行seed方法:
update-database
我們可以看到:
If you get an error that indicates a table already exists and can't be created, it is probably because you ran the application after you deleted the database and before you executedupdate-database
. In that case, delete theMovies.mdffile again and retry theupdate-database
command. If you still get an error, delete the migrations folder and contents
新聞熱點
疑難解答