我正在使用dotnet ef migrations add {MigrationName}
来创建新的迁移。
如果没有实体/上下文更改,则会创建一个包含空Up(MigrationBuilder migrationBuilder)
和Down(MigrationBuilder migrationBuilder)
函数的迁移。
migrations add
命令是否有办法跳过创建'空'文件?
或者,有没有办法在运行migrations add
命令之前检测是否有变化?
答案 0 :(得分:1)
我找到了解决这个问题的方法。
有一种方法create migrations programmatically而不是使用CLI。
查看MigrationsScaffolder source code后,我设法修改了第一个链接中的代码,以满足我的需求:
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<ISnapshotModelProcessor, SnapshotModelProcessor>()
.AddSingleton<MigrationsScaffolder>()
.BuildServiceProvider();
var scaffolderDependencies = designTimeServices.GetRequiredService<MigrationsScaffolderDependencies>();
var modelSnapshot = scaffolderDependencies.MigrationsAssembly.ModelSnapshot;
var lastModel = scaffolderDependencies.SnapshotModelProcessor.Process(modelSnapshot?.Model);
var upOperations = scaffolderDependencies.MigrationsModelDiffer.GetDifferences(lastModel, scaffolderDependencies.Model);
var downOperations = upOperations.Any() ? scaffolderDependencies.MigrationsModelDiffer.GetDifferences(scaffolderDependencies.Model, lastModel) : new List<MigrationOperation>();
if (upOperations.Count() > 0 || downOperations.Count() > 0)
{
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);
}
}
答案 1 :(得分:0)
我不知道它是否可能,但空迁移也很有用,就像你想手动运行任何脚本一样,例如,创建/改变StoredProcedures / Trigger。为此,您可以专门为特定目的生成空迁移。