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迁移可能导致数据丢失
相关推荐
loveandroid0 2020-06-18
wintershii 2020-06-07
blncle 2020-05-09
hxw0 2020-01-31
囧芝麻 2020-01-18
nan00zzu 2020-01-07
jusewe 2019-12-27
nan00zzu 2019-12-16
hufanglei00 2017-03-30
狗蛋的窝 2019-09-08
zhongzhiwei 2017-03-30
leiyanglove 2012-12-14
bluetears 2019-01-10
congdada 2019-06-26
兔子压倒窝边草 2019-06-25
boxue 2018-02-15
wlcome 2017-08-23