Enable Automatic Migrations for Entity Framework Core for SQL Databases without manual migration files. The package support following ways to apply/view-applied migrations: ### Context methods * Execute(TContext context); * Execute(TContext context, TMigrationsOptions options); * ExecuteAsync(TContext context, CancellationToken cancellationToken); * ExecuteAsync(TContext context, TMigrationsOptions options, CancellationToken cancellationToken); ### Extensions methods * MigrateToLatestVersion<TContext, TMigrationsOptions>(this TContext context); * MigrateToLatestVersion<TContext, TMigrationsOptions>(this TContext context, TMigrationsOptions options); * MigrateToLatestVersionAsync<TContext, TMigrationsOptions>(this TContext context, CancellationToken cancellationToken); * MigrateToLatestVersionAsync<TContext, TMigrationsOptions>(this TContext context, TMigrationsOptions options, CancellationToken cancellationToken);
$ dotnet add package EFCore.AutomaticMigrations
Enable Automatic Migrations for Entity Framework Core for SQL Databases without manual migration files..
<!-- USAGE EXAMPLES -->The package support following ways to apply/view-applied migrations:
DbMigrationsOptions object allows to configure migration options:
/// <summary>
/// Configuration options for automatic Entity Framework Core migrations.
/// </summary>
/// <remarks>
/// This class provides settings to control how automatic migrations are executed,
/// including data loss protection, schema reset capabilities, and snapshot management.
/// </remarks>
public class DbMigrationsOptions
{
/// <summary>
/// Gets or sets a value indicating whether automatic migrations that could result in data loss are allowed.
/// </summary>
/// <value>
/// <see langword="true"/> if data loss is allowed during migrations; otherwise, <see langword="false"/>.
/// Default is <see langword="false"/>.
/// </value>
/// <remarks>
/// When set to <see langword="false"/>, migrations that could potentially cause data loss
/// (such as dropping columns or tables) will throw an exception.
/// </remarks>
public bool AutomaticMigrationDataLossAllowed { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether automatic migrations are enabled.
/// </summary>
/// <value>
/// <see langword="true"/> if automatic migrations are enabled; otherwise, <see langword="false"/>.
/// Default is <see langword="true"/>.
/// </value>
public bool AutomaticMigrationsEnabled { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to reset the database schema by dropping all tables and recreating them.
/// </summary>
/// <value>
/// <see langword="true"/> to reset the database schema; otherwise, <see langword="false"/>.
/// Default is <see langword="false"/>.
/// </value>
/// <remarks>
/// <para>
/// When set to <see langword="true"/>, all existing tables will be dropped and recreated based on the current model.
/// This is useful during development, testing, or when working with transient data that can be safely discarded.
/// </para>
/// <para>
/// <strong>Warning:</strong> This will result in complete data loss. Use with caution in production environments.
/// </para>
/// </remarks>
public bool ResetDatabaseSchema { get; set; } = false;
/// <summary>
/// Gets or sets a dictionary of key-value pairs for updating the model snapshot.
/// </summary>
/// <value>
/// A dictionary where keys are replaced with their corresponding values in the snapshot.
/// Default is an empty dictionary.
/// </value>
/// <remarks>
/// This property allows for dynamic modification of the generated model snapshot code
/// by performing string replacements during the migration process.
/// </remarks>
public Dictionary<string, string> UpdateSnapshot { get; set; } = [];
/// <summary>
/// Gets or sets the database schema name for the migration history table.
/// </summary>
/// <value>
/// The schema name for the migration table, or <see langword="null"/> to use the model's default schema.
/// </value>
/// <remarks>
/// <para>
/// If not specified, the migration history table will be created in the same schema as defined by the model.
/// For SQL databases, this defaults to the "dbo" schema.
/// </para>
/// <para>
/// This property is particularly useful in multi-tenant scenarios or when working with specific database schemas.
/// </para>
/// </remarks>
public string Schema { get; set; }
}
// Get context
var app = builder.Build();
// begin apply automatic migration database to latest version
await using AsyncServiceScope serviceScope = app.Services.CreateAsyncScope();
await using DbContext? dbContext = serviceScope.ServiceProvider.GetService<DbContext>();
if (dbContext is not null)
{
// If the database context was successfully resolved from the service provider, we apply migrations.
// The DbMigrationsOptions object is used to configure automatic data loss prevention and offers other tools like viewing raw SQL scripts for migrations.
// we can list migration operations as raw sql before applying them and save them to a file or logs
var migrationsToApply = await dbContext.ListMigrationOperationsAsRawSqlAsync(cancellationToken: CancellationToken.None);
foreach (var migrationOperation in migrationsToApply.OrderBy(x => x.Order))
{
logger.LogInformation("Migration to apply: {SQL}. Is Destructive Change: {ISDESTRUCTIVECHANGE}.", migrationOperation.SqlCommand, migrationOperation.IsDestructiveChange);
}
// The database is created automatically if it does not exist, if exist will be updated to latest model changes
// Pay attention if you are using a PaaS database, like Azure; it will be created automatically using the default SKU and this might affect your costs.
var migrationOptions = new DbMigrationsOptions
{
AutomaticMigrationDataLossAllowed = true,
};
//execute migration to latest version
await dbContext.MigrateToLatestVersionAsync(migrationOptions);
//at this stage dabatabase containse latest changes
}/// <summary>
/// List applied migration
/// </summary>
/// <returns>List of applied migration</returns>
List<MigrationRaw> ListAppliedMigrations();
async Task<List<MigrationRaw>> ListAppliedMigrationsAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Use this method to list migration operations which will be applied as raw sql
/// </summary>
/// <returns>List of sql scripts. Empty list if no pending migrations, or database is not connected/created</returns>
List<MigrationOperationRaw> ListMigrationOperationsAsRawSql();
async Task<List<MigrationOperationRaw>> ListMigrationOperationsAsRawSqlAsync(CancellationToken cancellationToken = default);// begin apply automatic migration database to latest version
await using AsyncServiceScope serviceScope = app.Services.CreateAsyncScope();
await using TodoDbContext? dbContext = serviceScope.ServiceProvider.GetService<TodoDbContext>();
if (dbContext is not null)
{
// List migration operations as raw SQL commands
var sqlMigrationOperations = await dbContext.ListMigrationOperationsAsRawSqlAsync();
foreach (var sqlMigrationOperation in sqlMigrationOperations)
{
// log sql commands
Console.WriteLine(sqlMigrationOperation.SqlCommand);
}
// Apply migrations
await dbContext.MigrateToLatestVersionAsync();
// List applied migrations
List<MigrationRaw> appliedMigrations = await dbContext.ListAppliedMigrationsAsync();
foreach (MigrationRaw migration in appliedMigrations)
{
Console.WriteLine(migration.MigrationId);
}
}