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

  • 相关阅读:
    Sentinel-1雷达数据可以免费下载
    影像下载
    遥感影像下载地址
    ERS卫星
    alos 数据下载
    RMSE、RMS、标准差
    Landsat8数据不同波段组合的用途
    资源下载
    短视频录制的一个例子,拥有美颜滤镜、人脸贴纸功能。
    an iOS demo to demonstrate how to decorate face like faceu
  • 原文地址:https://www.cnblogs.com/tangchun/p/8334069.html
Copyright © 2011-2022 走看看