I develop c# .net 6 api on dev server and migrate some tables. I need to auto migrate missing migrations on production server when api started.
Asked
Active
Viewed 32 times
1 Answers
0
You can try to run context.Database.Migration()
in your Program.cs
. Here is an example:
app.Services.GetRequiredService<ContosoUniversityContext>().Database.Migrate();
Full example here:
using Microsoft.EntityFrameworkCore;
using WebApplication2.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<ContosoUniversityContext>(
options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
using (var serviceScope = app.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
var context = services.GetRequiredService<ContosoUniversityContext>();
await context.Database.MigrateAsync();
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Will Huang
- 2,955
- 2
- 37
- 90