ASP.NET Core 2种子数据库 [英] ASP.NET Core 2 Seed Database

查看:164
本文介绍了ASP.NET Core 2种子数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在SO上看到了一些类似的例子,但是我对这种语言的了解还不够,还无法了解我做错了什么。我已经拼凑了一个演示程序以了解更多信息,但是在播种数据库时遇到了麻烦。

I've seen some of the similar examples on SO regarding this but I don't know enough about the language just yet to see what I'm doing wrong. I've cobbled together a demo to learn more but I'm having trouble seeding my database.

我收到以下错误:


InvalidOperationException:无法从根提供程序解析作用域服务'demoApp.Models.AppDbContext'。

InvalidOperationException: Cannot resolve scoped service 'demoApp.Models.AppDbContext' from root provider.

Microsoft.Extensions.DependencyInjection .ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType,ServiceProvider serviceProvider)

Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)

以下是有问题的三个文件:

Here are the three files in question:

Models / AppDbContext.cs

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }
    public DbSet<Product> Products{ get; set; }
    public DbSet<Category> Categories { get; set; }
}

Models / DBInitializer.cs

public static class DbInitializer
{
    public static void Seed(IApplicationBuilder applicationBuilder)
    {
        //I'm bombing here
        AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>();

        if (!context.Products.Any())
        {
            // Add range of products
        }

        context.SaveChanges();
    }

    private static Dictionary<string, Category> _categories;
    public static Dictionary<string, Category> Categories
    {
        get
        {
            if (_categories == null)
            {
               // Add categories...
            }

            return _categories;
        }
    }
}

Startup.cs

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ICategoryRepository, CategoryRepository>();
    services.AddTransient<IProductRepository, ProductRepository>();

    services.AddDbContext<AppDbContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseStatusCodePages();

        // Kersplat!
        DbInitializer.Seed(app);
    }
    else ...

    app.UseStaticFiles();
    app.UseMvc(routes => {...});
}

有人可以帮忙解释我做错了什么以及如何解决这种情况?

Can someone help explain what I'm doing wrong and how to remedy the situation?

推荐答案

在ASP.NET Core 2.0中,建议进行以下更改。 (startup.cs中的播种适用于Core1.x。对于2.0,请进入Program.cs,修改Main方法以在应用程序启动时执行以下操作:
从依赖项注入容器中获取数据库上下文实例。
调用seed方法,并将其传递给上下文。
在种子方法完成后处置上下文。
(这里是Microsoft网站的示例。 https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-mvc / intro

In ASP.NET Core 2.0 the following changes are recommended. (Seeding in startup.cs works for Core 1.x. For 2.0 go into Program.cs, modify the Main method to do the following on application startup: Get a database context instance from the dependency injection container. Call the seed method, passing to it the context. Dispose the context when the seed method is done. (Here's a sample from the Microsoft site. https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro )

public static void Main(string[] args)
{
var host = BuildWebHost(args);

using (var scope = host.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    try
    {
        var context = services.GetRequiredService<yourDBContext>();
        DbInitializer.Seed(context);//<---Do your seeding here
    }
    catch (Exception ex)
    {
        var logger = services.GetRequiredService<ILogger<Program>>();
        logger.LogError(ex, "An error occurred while seeding the database.");
    }
}

host.Run();
}

这篇关于ASP.NET Core 2种子数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆