Sup*_*JMN 32 .net c# asp.net entity-framework asp.net-core
首先,我正在尝试使用示例数据为我的数据库设定种子.我已经读过这是这样做的方法(在Startup.Configure中)(请参阅ASP.NET Core RC2种子数据库)
我正在使用ASP.NET Core 2.0和默认选项.
像往常一样,我注册了我DbContext的ConfigureServices.但在那之后,在Startup.Configure方法中,当我尝试使用GetRequiredService它解决它时,它抛出此消息:
System.InvalidOperationException:'无法从根提供程序解析作用域服务'SGDTP.Infrastructure.Context.SGDTPContext'.
我的Startup类是这样的:
public abstract class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase"))
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
SeedDatabase(app);
}
private static void SeedDatabase(IApplicationBuilder app)
{
using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>())
{
// Seed the Database
//...
}
}
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?此外,这是创建种子数据的最佳位置吗?
Kir*_*kin 65
您正在注册SGDTPContext为范围服务,然后尝试在范围之外访问它.要为您的目的创建范围,可以使用以下解决方案:
using (var serviceScope = app.ApplicationServices.CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();
// Seed the database.
}
Run Code Online (Sandbox Code Playgroud)
这是一个讨论这种方法的旧Github 问题.
感谢@khellang指出SeedDatabase他评论中的扩展方法.
请参阅@ Tseng的评论和答案,了解如何最好地处理EF Core 2中的种子数据.
| 归档时间: |
|
| 查看次数: |
18052 次 |
| 最近记录: |