Enable-Migrations -EnableAutomaticMigration:$true
// -f 覆盖掉Migrations中的Configuration文件
Enable-Migrations -ContextType CusDbName -f
打开nuget
1、Enable-Migrations -EnableAutomaticMigration:$true
如果程序集中有多个CusDbContext会报错:
在程序集"assemblyname"中找到多个上下文类型
要允许 ”Model.CusDbContextName"的迁移,请使用Enable-Migrations -ContextTypeName CusContextName
解决办法:
Enable-Migrations -ContextTypeName CusDbName
生成文件
namespace x
{
internal sealed class Configuration:DbMigrationsConfiguration<CusDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled =true;
}
protected override void Seed(CusContext 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.
}
}
}
2、添加数据库初始化器到配置中
public class CusDbContext:DbContext
{
public CusDbContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<CusDbContext, Configuration>());
}
public virutal DbSet<Student> Students{get;set;}
public virtual DbSet<Standard> Standards{get;set;}
protected override void OnModelCreateing(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
中间会报错
未为提供程序“MySql.Data.MySqlClient”找到任何 MigrationSqlGenerator。请在目标迁移配置类中使用 SetSqlGenerator 方法以注册其他 SQL 生成
解决方法:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class CusDbContext:DbContext{}
当我们修改实体类时,运行程序就会自动迁移据库
跑下程序,试试看。
Enable-Migrations -ContextTypeName CusDbContext -f
nuget控制台
Add-Migration firstinit
会在Migrations文件夹中生成<当前时间>_name的迁移类
namespace EfDemo.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class firstinit : DbMigration
{
//升级
public override void Up()
{
CreateTable(
"dbo.account",
c => new
{
Id = c.Long(nullable: false, identity: true),
serial = c.String(unicode: false),
type = c.String(unicode: false)
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.after",
c => new
{
Id = c.Int(nullable: false, identity: true),
uid = c.String(unicode: false),
customer = c.String(unicode: false)
})
.PrimaryKey(t => t.Id);
}
//回退
public override void Down()
{
DropTable("dbo.test");
}
}
}
会执行add-migration 创建的数据迁移文件,并更新数据库。执行完到此,数据库已经生成了。
如果修改某个实体类,执行add-migration migname,再执行update-database -verbose,就可以方便的根据模型的变化更新数据库。
回退到某个版本,比如回退到firstinit版本
update-database -verbose -targetmigration:firstinit。
update-databse -verbose -f
Entity Framework Code First 设计工具安装