如何更改迁移生成器EF CORE 2.x?

时间:2019-08-20 08:44:13

标签: c# entity-framework-core ef-core-2.2

我需要在迁移生成器中添加一些功能,并在迁移中自动添加InsertData。

我已经创建了自定义CSharpMigrationsGenerator,但是我不知道如何以及在哪里注册。

public class CustomCSharpMigrationCodeGenerator : CSharpMigrationsGenerator
    {
        public override string GenerateMigration(string migrationNamespace, 
            string migrationName, 
            IReadOnlyList<MigrationOperation> upOperations, 
            IReadOnlyList<MigrationOperation> downOperations)
        {
            throw new Exception("Hello world");
            return base.GenerateMigration(migrationNamespace, migrationName, upOperations, downOperations);
        }

        public CustomCSharpMigrationCodeGenerator(MigrationsCodeGeneratorDependencies dependencies, 
            CSharpMigrationsGeneratorDependencies csharpDependencies) : base(dependencies, csharpDependencies)
        {
            throw new Exception("Hello world");
        }
    }

我尝试了这个,但是没用

public class MyDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<CSharpMigrationsGenerator, CustomCSharpMigrationCodeGenerator>();
    }
}

我需要在哪里注册?还是我使用了错误的课程?

1 个答案:

答案 0 :(得分:0)

您快到了。此类实现的服务(您需要替换)只是IMigrationsCodeGenerator

public class MyDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<IMigrationsCodeGenerator, CustomCSharpMigrationCodeGenerator>();
    }
}