EF CodeFirst Mode Automatic migration (applicable to the development environment), efcodefirst
Automatic migration in CodeFirst mode of EF (applicable to the development environment)
1. Enable EF data migration
NuGet Package Manager ------> package management console --------> Enable-Migrations
2. Set the database context to migrate to the last version.
MigrateDatabaseToLatestVersion <database context, migration Configuration File>
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; // obtain the SQL executed by EF} // <summary> // release the resource /// </summary> public new void Dispose () {base. dispose (); GC. SuppressFinalize (this);} // <summary> // destructor /// </summary> ~ AppDBContext () {base. dispose ();} private void GetLog (string SQL) {// log output to the console System. diagnostics. debug. write (SQL);} protected override void OnModelCreating (DbModelBuilder modelBuilder) {// solve the problem that the name of the database table in the EF dynamic database is changed to the plural modelBuilder. conventions. remove <PluralizingTableNameConvention> ();}}
3. Configure the migration configuration file to allow automatic migration andData loss is allowed during migration (only applicable to the development environment)
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. } }}
Entity changes. Manual migration is no longer required. The database will be automatically updated. Setting AutomaticMigrationDataLossAllowed to true for migration may cause data loss.