0

I'm rewriting a simple application that uses Asp.NET 5. but now I'm using Asp.NET 6 for the new version of my app. Quick question: what's the replacement of database auto migration (like below in .NET5) in .NET6 or What approach should I use for automatic migration after application launch in .NET6?

Sample in .NET5:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, PgSqlDbContext context)
    {
        context.Database.Migrate();
        /*
         other middlewares
        */
    }

.NET6 :

var app = builder.Build();
// ???? for auto migration
// other middlewares
happykratos
  • 112
  • 8
  • Does this answer your question? [.NET 6 how to run Migration automatically in program.cs](https://stackoverflow.com/questions/70266442/net-6-how-to-run-migration-automatically-in-program-cs) – Okan Karadag Apr 18 '22 at 11:45

2 Answers2

3

I have tried to add this code and the project works successfully.

var app = builder.Build();

using (var serviceScope = app.Services.CreateScope())
{
   var services = serviceScope.ServiceProvider;
    
   var dbcontext = services.GetRequiredService<PgSqlDbContext>();
   var conn = dbcontext.Database.GetConnectionString();
}
//other middlewares
Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • If my answer help you resolve your issue, could you please accept as answer? Refer to:[How to accept as answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). Thank you very much. – Xinran Shen Jan 21 '22 at 07:27
0

Here's my translation from Microsoft's Docs on 5 to 6 migration to your use case:

var app = builder.Build();
var context = app.Services.GetRequiredService<PgSqlDbContext>();
context.Database.Migrate();

I did not test this, so fingers crossed!

Uxonith
  • 1,602
  • 1
  • 13
  • 16
  • thanks, but it did not work, cause the DI-Container can not find an instance of DbContext, Why? IDK. anyway, I handled it somewhere else in my application, but if you came up with any probable solution let me know. – happykratos Jan 19 '22 at 19:35
  • @happykratos I'm assuming you are registering it like `builder.Services.AddDbContext(options => options.UseNpgsql(builder.Configuration.GetConnectionString("PgSqlDbContext")));` before `builder.Build()`? – Uxonith Jan 20 '22 at 01:07
  • yup, that's what I used – happykratos Jan 20 '22 at 08:27