entity-framework - 具有自定义迁移基础的 Entity Framework 添加迁移脚手架

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

我需要使用来自 DbMigration 的自定义迁移基础 CustomMigration 从程序包管理器控制台使用 add-migration 搭建迁移脚手架。

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

    public override void Down()
    {
    }
}

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

最佳答案

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

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/

关于entity-framework - 具有自定义迁移基础的 Entity Framework 添加迁移脚手架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36907120/

相关文章:

c# - 在 CSharpMigrationCodeGenerator 中使用自定义 MigrationOperation

c# - EF Core2.2 : Scaffold-DbContext not working with named connection string in WPF project

.net - 如何回滚实体删除而不丢失导航属性

entity-framework - EF 5 模型第一部分类自定义构造函数如何?

c# - Code First 和 DBContext 的多态性

c# - 如何使用 GraphDiff 更新相关实体?

c# - Entity Framework Core - 如何访问 Context.Database.Migrate()

c# - 使用结构而不是类的 EntityFramework SqlQuery 失败并出现 ArgumentException

c# - 使用 MySql 的 Entity Framework : Map System. VARCHAR(40) 指南

c# - EF Code First 数据库迁移中的 DbMigrator 需要访问主数据库