EF的CodeFirst模式自動遷移(適用於開發環境) 1、開啟EF數據遷移功能 NuGet包管理器 >程式包管理控制台 >Enable-Migrations 2、資料庫上下文設置為遷移至最後一個版本 MigrateDatabaseToLatestVersion<資料庫上下文,遷移配置文件> 3、設 ...
EF的CodeFirst模式自動遷移(適用於開發環境)
1、開啟EF數據遷移功能
NuGet包管理器------>程式包管理控制台---------->Enable-Migrations
2、資料庫上下文設置為遷移至最後一個版本
MigrateDatabaseToLatestVersion<資料庫上下文,遷移配置文件>
using Models.Migrations; namespace Models { public class AppDBContext : DbContext, IDisposable { static AppDBContext() { Database.SetInitializer<AppDBContext>(new MigrateDatabaseToLatestVersion<AppDBContext, Configuration>()); } public AppDBContext() : base("DefaultConnection") { Database.Log = GetLog; //獲取EF執行的sql } /// <summary> /// 釋放資源 /// </summary> public new void Dispose() { base.Dispose(); GC.SuppressFinalize(this); } /// <summary> /// 析構函數 /// </summary> ~AppDBContext() { base.Dispose(); } private void GetLog(string sql) { //日誌輸出到控制台 System.Diagnostics.Debug.Write(sql); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { //解決EF動態建庫資料庫表名變為複數問題 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } }
3、設置遷移配置文件,允許自動遷移和允許遷移時數據丟失(只適用於開發環境)
namespace Models.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<Models.AppDBContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; ContextKey = "Models.AppDBContext"; } protected override void Seed(Models.AppDBContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } } }
實體變動,不再需要手動遷移,資料庫將自動更新,AutomaticMigrationDataLossAllowed 設置為true遷移可能導致數據丟失