Entity framework 添加带有自定义迁移基础的迁移脚手架

Entity framework add-migration scaffold with custom Migration base

我需要使用来自包管理器控制台的 add-migration 和我的自定义迁移基础 CustomMigration 搭建迁移脚手架,它源自 DbMigration.

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

    public override void Down()
    {
    }
}

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

  1. 运行 命令 add-migration NewMigration。它将添加名称为 "NewMigration" 的新迁移。如果模型没有变化,迁移将为空:

    public partial class NewMigration : DbMigration
    {
        public override void Up()
        {
        }
    
        public override void Down()
        {
        }
    }
    
  2. 将 NewMigration 的基础 class 更改为 CustomMigration:

    public partial class NewMigration : CustomMigration
    {
        public override void Up()
        {
        }
    
        public override void Down()
        {
        }
    }
    
  3. 根据需要修改NewMigration
  4. 运行 update-database 应用迁移

我创建了新的 class 生成了我的迁移:

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/