Migrating Database on App Startup with Entity Framework
Entity Framework migrations are a great way to keep your database schema in sync with your data model. For local and development environments, automatically running migrations at startup can simplify your workflow significantly.
Implementation with Environment Guards
Let’s look at properly guarded migration code for different application types.
Implementing this is ASP.NET
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// Only migrate in development environment
if (app.Environment.IsDevelopment())
{
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
Console.WriteLine("Database migrations applied successfully");
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Error applying database migrations");
}
}
}
app.Run();
Production Warning
For production environments, never automatically apply migrations at startup. Instead:
- Run migrations as a separate, controlled deployment step
- Use database deployment tools or migration scripts
- Ensure proper backups before schema changes
Remember, this approach is intended only for local development and testing environments where database consistency is prioritized over startup performance and control.
csharp entity-framework asp.net dotnet
2025-04-03
Read other posts