.net Mvc Code First 模式 模型修改自动同步到数据库

C#

浏览数:59

2019-8-30

使用nuget 添加EntityFramework 引用

引入命名空间

using System.Data.Entity;
using System.Data.Entity.Migrations;

关键代码

internal sealed class MainDbMigrationsConfiguration: DbMigrationsConfiguration<MainDbContext>
 {
    public MainDbMigrationsConfiguration()
     {
        //默认情况下不会自动迁移数据库结构
        //设置为true则自动迁移数据库结构
         AutomaticMigrationsEnabled = true;
     }
}

完整的类大概是这个样子

using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace ManageSystem.Core
{
    public class MainDbContext : DbContext
    {
        public MainDbContext() : base()
        {
            Database.SetInitializer<MainDbContext>(new MigrateDatabaseToLatestVersion<MainDbContext, MainDbMigrationsConfiguration>());
        }
        public MainDbContext(string connectionName) : base(connectionName)
        {
            Database.SetInitializer<MainDbContext>(new MigrateDatabaseToLatestVersion<MainDbContext, MainDbMigrationsConfiguration>());
        }
        internal sealed class MainDbMigrationsConfiguration: DbMigrationsConfiguration<MainDbContext>
        {
            public MainDbMigrationsConfiguration()
            {
                AutomaticMigrationsEnabled = true;
            }
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
        }
    }
}

这种方式主要是将原本独立出来的类合并到DbContext中来.
更常规一点的做法是把下面这段代码独立出来,放在一个类里面方便后期维护

internal sealed class MainDbMigrationsConfiguration: DbMigrationsConfiguration<MainDbContext>
        {
            public MainDbMigrationsConfiguration()
            {
                AutomaticMigrationsEnabled = true;//任何Model Class的修改将会直接更新DB
                AutomaticMigrationDataLossAllowed = true;
            }
        }

作者:这个用户有点逗