EF Core添加迁移调试

时间:2017-01-15 16:39:06

标签: c# entity-framework ef-code-first database-migration entity-framework-core

如何使用断点进入OnModelCreating并查看我的逻辑是否错误或者ModelBuilder是否正在做我不期望的事情?我已经看过很多关于如何调试实际迁移的帖子,但没有关于如何观察如何生成模型代码的帖子。

我正在尝试在我的某些实体上实现一些自定义属性,并且它被忽略了;我希望看到我的配置在生成模型代码时正在做什么。

2 个答案:

答案 0 :(得分:20)

您应该可以在代码中调用Debugger.Launch()。即时调试器应该在它到达该行时提示您附加调试器。

答案 1 :(得分:0)

另一种方法是创建自己的控制台应用程序或对它进行单元测试和调试。使用bricelam from the ef github issue

的代码段
using (var db = new MyDbContext())
{
    var reporter = new OperationReporter(
        new OperationReportHandler(
            m => Console.WriteLine("  error: " + m),
            m => Console.WriteLine("   warn: " + m),
            m => Console.WriteLine("   info: " + m),
            m => Console.WriteLine("verbose: " + m)));

    var designTimeServices = new ServiceCollection()
        .AddSingleton(db.GetService<IHistoryRepository>())
        .AddSingleton(db.GetService<IMigrationsIdGenerator>())
        .AddSingleton(db.GetService<IMigrationsModelDiffer>())
        .AddSingleton(db.GetService<IMigrationsAssembly>())
        .AddSingleton(db.Model)
        .AddSingleton(db.GetService<ICurrentDbContext>())
        .AddSingleton(db.GetService<IDatabaseProvider>())
        .AddSingleton<MigrationsCodeGeneratorDependencies>()
        .AddSingleton<ICSharpHelper, CSharpHelper>()
        .AddSingleton<CSharpMigrationOperationGeneratorDependencies>()
        .AddSingleton<ICSharpMigrationOperationGenerator, CSharpMigrationOperationGenerator>()
        .AddSingleton<CSharpSnapshotGeneratorDependencies>()
        .AddSingleton<ICSharpSnapshotGenerator, CSharpSnapshotGenerator>()
        .AddSingleton<CSharpMigrationsGeneratorDependencies>()
        .AddSingleton<IMigrationsCodeGenerator, CSharpMigrationsGenerator>()
        .AddSingleton<IOperationReporter>(reporter)
        .AddSingleton<MigrationsScaffolderDependencies>()
        .AddSingleton<MigrationsScaffolder>()
        .BuildServiceProvider();

    var scaffolder = designTimeServices.GetRequiredService<MigrationsScaffolder>();

    var migration = scaffolder.ScaffoldMigration(
        "MyMigration",
        "MyApp.Data");

    File.WriteAllText(
        migration.MigrationId + migration.FileExtension,
        migration.MigrationCode);
    File.WriteAllText(
        migration.MigrationId + ".Designer" + migration.FileExtension,
        migration.MetadataCode);
    File.WriteAllText(migration.SnapshotName + migration.FileExtension,
        migration.SnapshotCode);
}