具有自定义迁移基础的实体框架添加迁移支架

时间:2016-04-28 06:40:49

标签: entity-framework ef-code-first ef-migrations

我需要使用来自add-migration的自定义迁移基础CustomMigration,在程序包管理器控制台中使用DbMigration进行迁移。

public partial class NewMigration: CustomMigration
{
    public override void Up()
    {
    }

    public override void Down()
    {
    }
}

如果需要,我可以使用不同的命令。我在PowerShell脚本编写方面没有任何技能。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:3)

我创建了一个生成迁移的新类:

public class AuditMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
    protected override void WriteClassStart(string @namespace, string className, IndentedTextWriter writer, string @base, bool designer = false, IEnumerable<string> namespaces = null)
    {
        @base = @base == "DbMigration" ? "AuditMigration" : @base;
        var changedNamespaces = namespaces?.ToList() ?? new List<string>();
        changedNamespaces.Add("Your.Custom.Namespace");
        base.WriteClassStart(@namespace, className, writer, @base, designer, changedNamespaces);
    }
}

在Configuration.cs中:

internal sealed class Configuration : DbMigrationsConfiguration<EfDataAccess>
{
    public Configuration()
    {
        this.AutomaticMigrationsEnabled = false;
        CodeGenerator = new AuditMigrationCodeGenerator();
    }
}

它将使用您的自定义代码生成器,它使用我想要的自定义迁移基础生成迁移。

了解更多信息:https://romiller.com/2012/11/30/code-first-migrations-customizing-scaffolded-code/

答案 1 :(得分:0)

  1. 运行命令Colors.SelectedIndex = "element found"; 。它将添加名为“NewMigration”的新迁移。如果模型中没有更改,则迁移将为空:

    add-migration NewMigration
  2. 将NewMigration的基类更改为CustomMigration:

    public partial class NewMigration : DbMigration
    {
        public override void Up()
        {
        }
    
        public override void Down()
        {
        }
    }
    
  3. 根据需要修改NewMigration
  4. 运行public partial class NewMigration : CustomMigration { public override void Up() { } public override void Down() { } } 以应用迁移
相关问题