using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.Extensions.DependencyInjection;
namespace Elsa.Persistence.EFCore.UnitTests;
///
/// Generates a migration script offline, through , so tests can assert on the
/// SQL a migration produces without opening a database connection.
///
internal static class MigrationScriptGenerator
{
///
/// Builds a configured by and generates the
/// migration script between and .
///
/// Configures the provider (and, through it, the migrations assembly and schema) on the options builder.
/// The migration to generate the script from, or null for the initial database state.
/// The migration to generate the script up to.
/// The SQL generation options, for example whether the script is idempotent.
public static string Generate(
Action> configure,
string? fromMigration,
string toMigration,
MigrationsSqlGenerationOptions options)
where TDbContext : DbContext
{
var optionsBuilder = new DbContextOptionsBuilder();
configure(optionsBuilder);
var serviceProvider = new ServiceCollection().BuildServiceProvider();
using var dbContext = (TDbContext)Activator.CreateInstance(typeof(TDbContext), optionsBuilder.Options, serviceProvider)!;
return dbContext.GetService().GenerateScript(fromMigration: fromMigration, toMigration: toMigration, options: options);
}
}