This can be achieved by extending the standard EFCore migrator implementation:
public class CustomMigrator : Migrator
{
public CustomMigrator (
IMigrationsAssembly migrationsAssembly,
IHistoryRepository historyRepository,
IDatabaseCreator databaseCreator,
IMigrationsSqlGenerator migrationsSqlGenerator,
IRawSqlCommandBuilder rawSqlCommandBuilder,
IMigrationCommandExecutor migrationCommandExecutor,
IRelationalConnection connection,
ISqlGenerationHelper sqlGenerationHelper,
ICurrentDbContext currentContext,
IModelRuntimeInitializer modelRuntimeInitializer,
IDiagnosticsLogger<DbLoggerCategory.Migrations> logger,
IRelationalCommandDiagnosticsLogger commandLogger,
IDatabaseProvider databaseProvider) : base(migrationsAssembly, historyRepository, databaseCreator, migrationsSqlGenerator, rawSqlCommandBuilder, migrationCommandExecutor, connection, sqlGenerationHelper, currentContext, modelRuntimeInitializer, logger, commandLogger, databaseProvider)
{
_connection = connection;
}
IRelationalConnection _connection;
public override void Migrate(string? targetMigration = null)
{
base.Migrate(targetMigration);
if (!_connection.DbConnection.State.HasFlag(ConnectionState.Open))
{
_connection.Open();
}
using var command = _connection.DbConnection.CreateCommand();
command.CommandText = "create or replace view v_aaa as select 1 as aaa";
command.ExecuteNonQuery();
}
public override async Task MigrateAsync(string? targetMigration = null, CancellationToken cancellationToken = default)
{
await base.MigrateAsync(targetMigration, cancellationToken);
if (!_connection.DbConnection.State.HasFlag(ConnectionState.Open))
{
await _connection.OpenAsync(cancellationToken);
}
using var command = _connection.DbConnection.CreateCommand();
command.CommandText = "create or replace view v_aaa as select 1 as aaa";
await command.ExecuteNonQueryAsync();
}
}
The service should be substituted as follows:
builder.Services.AddDbContext<TDbContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString(connectionStringName));
options.ReplaceService<IMigrator, CustomMigrator>();
});