EF Core dbcontext scaffolder不会触发OperationReportHandler事件

时间:2018-01-29 12:56:55

标签: c# entity-framework .net-core entity-framework-core

我编写了.NET Core dbcontext scaffolder方法来生成实体类和DbContext。一切正常,但errorList,warningList,infoList,verboseList总是空的...如何解决OperationReportHandler工作?

        var errorList = new List<string>();
        var warningList = new List<string>();
        var infoList = new List<string>();
        var verboseList = new List<string>();

        var reporter = new OperationReporter(
                        new OperationReportHandler(
                            m => errorList.Add((m)),
                            m => warningList.Add((m)),
                            m => infoList.Add((m)),
                            m => verboseList.Add((m))));

        var serviceCollection = new ServiceCollection()
            .AddScaffolding(reporter)
            .AddSingleton<IOperationReporter, OperationReporter>()
            .AddSingleton<IOperationReportHandler, OperationReportHandler>();

        IDesignTimeServices provider = new Microsoft.EntityFrameworkCore.Design.Internal.SqlServerDesignTimeServices();
        provider.ConfigureDesignTimeServices(serviceCollection);

        var serviceProvider = serviceCollection.BuildServiceProvider();

        var generator = serviceProvider.GetService<IModelScaffolder>();

        var filePaths = generator.Generate(
                                    Config.ConnectionString,
                                    Config.Tables,
                                    Config.Schemas,
                                    Config.ProjectPath,
                                    Config.OutputPath,
                                    Config.RootNamespace,
                                    Config.ContextName,
                                    false, //useDataAnnotations
                                    Config.OverwriteFiles,
                                    Config.UseDatabaseNames);

1 个答案:

答案 0 :(得分:1)

更改此行...

.AddSingleton<IOperationReporter, OperationReporter>()

......对此。

.AddSingleton<IOperationReporter>(reporter)

P.S。这在EF Core 2.1中更简单:

var serviceCollection = new ServiceCollection()
    .AddEntityFrameworkDesignTimeServices(reporter);