2017-09-05 37 views
9

首先,我试图给我的数据库添加样本数据。我已经阅读,这是做到这一点的方式(在Startup.Configure)(请参阅ASP.NET Core RC2 Seed Database无法解析ASP.NET核心2.0中的DbContext

我正在使用ASP.NET Core 2.0的默认选项。

和往常一样,我在ConfigureServices注册我的DbContext。 但在那之后,在Startup.Configure方法,当我尝试它使用GetRequiredService解决,它抛出此消息:

System.InvalidOperationException:“无法解析范围的服务 ” SGDTP.Infrastructure.Context。 SGDTPContext'从根 供应商'。

我的启动类是这样的:

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

我在做什么错? 此外,这是创建种子数据的最佳场所吗?

回答

11

您正在注册SGDTPContext作为范围服务,然后尝试访问范围外的。为了创建你的目的范围,则可以采用如下方案:

using (var serviceScope = app.ApplicationServices.CreateScope()) 
{ 
    var context = serviceScope.ServiceProvider.GetService<SGDTPContext>(); 
    // Seed the database. 
} 

这里是一个老Github上issue,讨论这种方法。

感谢@khellang在他的评论中指出了CreateScope扩展方法。

见@曾国藩的意见和answer为解释如何最好地在EF核心接近播种数据2.

+0

你是男人。非常感谢您的信息。你拯救了生命! – SuperJMN

+1

_does似乎仍然是我所见过的播种的推荐方法_那么,不完全是。使用有范围的是,但不在配置方法内,请按照EF Core 2.0在设计时发现和实例化DbContext的方式进行操作。有关当前推荐的方法,请参阅https://stackoverflow.com/a/45942026/455493。如果你继续在'Configure'方法中进行播种,那么运行'dotnet ef migrations'或'dotnet ef database update'也会执行播种,这是你在运行命令行工具时几乎不想要的东西 – Tseng

+0

Just FYI;直接在'IServiceProvider'上有一个'CreateScope'扩展方法](https://github.com/aspnet/DependencyInjection/blob/88c3bd6fe2786dd759b4a6c6d7c410e895336b6c/src/DI.Abstractions/ServiceProviderServiceExtensions.cs#L120-L128),所以你可以切割'。GetRequiredService ()'并直接调用它:) – khellang

0

当时得到这个错误,而下面的官方ASP.Net MVC核心tutorial,在部分,在那里你应该将种子数据添加到您的应用程序。长话短说,将这两行

using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.DependencyInjection; 

SeedData类解决了这个问题对我来说:

using Microsoft.EntityFrameworkCore; 
using Microsoft.Extensions.DependencyInjection; 
using System; 
using System.Linq; 

namespace MvcMovie.Models 
{ 
public static class SeedData 
{ 
    public static void Initialize(IServiceProvider serviceProvider) 
    { 
     using (var context = new MvcMovieContext(

      serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>())) 
     { 
      // Look for any movies. 
      if (context.Movie.Any()) 
      { 
       return; // DB has been seeded 
      } 
    ... 

不能告诉你该干嘛,但是这两个的我从下面得到的选项Alt + Enter快速修复选项。

相关问题