1. 程式人生 > 其它 >Entity FrameWork Code First 之 MVC4 資料庫初始化策略用法

Entity FrameWork Code First 之 MVC4 資料庫初始化策略用法

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

通過啟用遷移和更新資料庫可以很容易的生成一張表。但是對資料庫修改之後,通過資料遷移就沒那麼好實現了。

這裡用到資料庫生成策略,進行對資料庫操作:

一、3種主要資料庫生成策略

1CreateDatabaseIfNotExists方法會在沒有資料庫時建立一個,這是預設行為。

Database.SetInitializer(CreateDatabaseIfNotExists<xxx>());

2DropCreateDatabaseIfModelChanges如果我們在在模型改變時,自動重新建立一個新的資料庫,就可以用這個方法。在這開發過程中非常有用。

Database.SetInitializer(DropCreateDatabaseIfModelChanges<xxx>());

3DropCreateDatabaseAlways如果你想在每次執行時都重新生成資料庫就可以用這個方法。

Database.SetInitializer(DropCreateDatabaseAlways<xxx>());

修改資料庫之後重新生成資料庫,推薦使用DropCreateDatabaseAlways

詳細用法:

1).Global.asax:Application_Start()方法中新增:

Database.SetInitializer<ManagementDBContext>(DropCreateDatabaseAlways<ManagementDBContext>());

  ManagementDBContext為自己定義的Context上下文。

2).然後刪除專案中啟用資料遷移自動生成的資料夾:Migrations及下面所有內容

  不刪除會報一個 The DropCreateDatabaseAlways initializer did not drop or create the database backing context 'ManagementDBContext' because Migrations are enabled for the context. Use Migrations to manage the database for this context, for example by running the 'Update-Database' command from the Package Manager Console. 錯誤。

3).最後在程式碼中使用db物件,即可重新生成資料庫。

複製程式碼

(ManagementDBContextdb=result=

複製程式碼

二、自定義生成策略

自定義策略主要用的自定義策略中重寫的Seed方法。

可以在Seed方法中加一些初始資料,這樣生成的時候就會生成初始資料。

複製程式碼

ManagementDBContextInitializer:DropCreateDatabaseAlways<ManagementDBContext>roles=List<Role>=====>

轉載於:https://my.oschina.net/jackguo/blog/315894