zoukankan      html  css  js  c++  java
  • EF的CodeFirst模式自动迁移(适用于开发环境)

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

  • 相关阅读:
    面试题目整理(MySQL系列-调优)
    面试题目整理(MySQL系列-事务)
    面试题目整理(MySQL系列-索引)
    MySQL遇到问题
    Gorm的高级用法
    Gorm的初步使用(使用频率排序)
    MySQL索引详解
    SSH命令行上传/下载文件
    SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,COERCIBLE) for operation 'like' 。。。
    Redis 缓存穿透、缓存雪崩、缓存击穿解决方案
  • 原文地址:https://www.cnblogs.com/tangchun/p/8334069.html
Copyright © 2011-2022 走看看