首先,我试图在我的数据库中植入样本数据.我已经读到这是做这件事的方法(在Startup.Configure)(请看ASP.NET Core RC2 Seed Database)

我在用ASP.NET Core 2.0和默认选项.

和往常一样,我在ConfigureServices中登记了我的DbContext分.

系统InvalidOperationException:'无法解析作用域服务

我的创业课程是这样的:

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
            //... 
        }
    }
}

我做错了什么?

推荐答案

您正在将SGDTPContext注册为scoped服务,然后try 访问作用域的outside.要在SeedDatabase方法内创建作用域,请使用以下方法:

using (var serviceScope = app.ApplicationServices.CreateScope())
{
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>();

    // Seed the database.
}

感谢@khellang在 comments 中指出了CreateScope扩展方法,以及@Tseng的 comments 和answer Re如何在EF Core 2中实现种子.

Asp.net相关问答推荐

502 DotNet WebApplication的网关nginx已损坏

如何使用 Get-Process powershell 命令通过端口号获取进程的 ID

无法翻译 LINQ

如何在 IIS 上配置 Web Deploy 发布功能,以便开发人员可以发布?

*不*使用 asp.net 会员提供程序是个坏主意吗?

Firefox 和 Chrome 之间 1 像素的行高差

在 Sessions 中存储自定义对象

从 RowDataBound 事件的 gridview 从单元格中获取值

在 Blazor 中 Select 框绑定

我应该如何在类和应用层之间传递数据?

问题映射 HttpHandler --> HTTP Error 404 Not Found

svg 无法在 localhost 上的 IIS 网络服务器上运行

ASP.NET web.config:system.web.compilation 中的 debug 属性的默认值是什么?

如何将参数传递给 ASP.NET MVC 2 中的自定义 ActionFilter?

ASP.Net 错误:应用程序池的标识无效

哪个控件导致了回发?

IISExpress 找不到使用 Visual Studio 2013 运行 localhost 的 ssl 页面

如何告诉 RadioButtonList 不生成表格

ASP.NET 邮箱验证器正则表达式

System.Drawing.Image.FromFile() 上的内存不足异常