当前位置: 移动技术网 > IT编程>开发语言>.net > EF的CodeFirst模式自动迁移(适用于开发环境)

EF的CodeFirst模式自动迁移(适用于开发环境)

2018年01月25日  | 移动技术网IT编程  | 我要评论

仙意通玄,果冻三剑客1,湖南卫视在线直播观看今晚

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迁移可能导致数据丢失

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网