update db entity framework code example

Example 1: entity framework update database automatically

public static IHost MigrateDbContext(
    this IHost host,
    Action seeder = null)
    where TContext : DbContext
{
    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        var logger = services.GetRequiredService>();
        var context = services.GetService();

        try
        {
            logger.LogInformation($"Migrating database associated with context {typeof(TContext).Name}");
            var retry = Policy.Handle().WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(5),
                TimeSpan.FromSeconds(10),
                TimeSpan.FromSeconds(15),
            });

            retry.Execute(() =>
            {
                context.Database.Migrate();
            });
            logger.LogInformation($"Migrated database associated with context {typeof(TContext).Name}");
        }
        catch (Exception ex)
        {
            logger.LogError(ex, $"An error occurred while migrating the database used on context {typeof(TContext).Name}");
        }
    }

    return host;
}

Example 2: how to update model in entity framework db first approach

Scaffold-DbContext "Server=(localdb)\v11.0;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

Tags:

Misc Example