[英]How do you do database.ensurecreated() in aspnet core web application using .NET 6?
In a .NET 5 web application, we use code such as the following in startup.cs to initialize the DB using Entity Framework:在 .NET 5 Web 应用程序中,我们在 startup.cs 中使用如下代码来使用 Entity Framework 初始化 DB:
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.EnsureCreated();
}
In .NET 6 though, I get the error that there is no ApplicationServices.但是在 .NET 6 中,我收到没有 ApplicationServices 的错误。 I tried the solution proposed here , but then I get a runtime error: 'Cannot resolve scoped service 'WebApplication1.DataAccess.SchoolDbContext' from root provider'.
我尝试了此处提出的解决方案,但随后出现运行时错误:'无法从根提供程序解析范围服务'WebApplication1.DataAccess.SchoolDbContext'。 The complete code in my program.cs is as follows:
我的program.cs中的完整代码如下:
using WebApplication1.DataAccess;
using Microsoft.EntityFrameworkCore;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddJsonFile("appsettings.json");
builder.Services.AddRazorPages();
// Setup EF connection
// https://stackoverflow.com/a/43098152/1385857
// https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab
builder.Services.AddDbContext<SchoolDbContext>(options =>
options.UseSqlServer(builder.Configuration["Data:SchoolLocal:ConnectionString"]));
WebApplication app = builder.Build();
// https://stackoverflow.com/a/71258326/1385857
SchoolDbContext dbcontext = app.Services.GetRequiredService<SchoolDbContext>();
dbcontext.Database.EnsureCreated();
...
Help would be great.帮助会很棒。
You can also use the async version of the CreateScope() method.您还可以使用 CreateScope() 方法的异步版本。 If you want to call an awaitable method.
如果你想调用一个等待的方法。
using(var scope = app.Services.CreateAsyncScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
//more codes ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.