How to access DbContext in .NET 6 minimal API Program.cs

com*_*p32 14 c# entity-framework-core .net-6.0 minimal-apis

I am trying to call EF Core methods on application startup in my Program.cs file, using the .NET 6 minimal API template and get the following error:

System.InvalidOperationException: 'Cannot resolve scoped service 'Server.Infrastructure.DbContexts.AppDbContext' from root provider.'

// ************** Build Web Application **************

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseNpgsql(configuration.GetConnectionString("AppDb:Postgres")));

// ...

// **************** Web Application *****************

var app = builder.Build();

var dbContext = app.Services.GetService<AppDbContext>(); // error thrown here

if (dbContext != null)
{
    dbContext.Database.EnsureDeleted();
    dbContext.Database.Migrate();
}

// ...
Run Code Online (Sandbox Code Playgroud)

With earlier versions of .NET Core I am aware I can get the DbContext in the Configure method, but how would I get the service with this approach?

Gur*_*ron 27

范围服务需要解决范围问题。您可以通过以下方式创建范围ServiceProviderServiceExtensions.CreateScope

using(var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    // use context
}
Run Code Online (Sandbox Code Playgroud)

  • 该死的所有这些变化...我花了很多时间在谷歌上搜索使用实体框架核心 6 设置 ASP.NET 核心 6。感谢您的回答! (2认同)