迁移到3.0后,无法创建从IdentityDBContext继承的ApplicationDbContext类型的对象

时间:2019-10-19 08:32:51

标签: asp.net-core entity-framework-core ef-core-3.0

当我尝试在迁移到 .net core 3.0和ef core 3.0 之后添加迁移时,出现错误:无法创建类型为'ApplicationDbContext'的对象。

enter image description here

依赖关系如下:

enter image description here

我的代码如下:

ApplicationDbContext.cs

  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, ILocalizationDbContext
{
    private readonly IServiceProvider _serviceProvider;

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }        

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options,
        IServiceProvider serviceProvider)
        : base(options)
    {
        _serviceProvider = serviceProvider;
    } 
   }

Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection"), 
                b => b.MigrationsAssembly("Infrastructure")), 
            ServiceLifetime.Transient);

        services.AddDefaultIdentity<ApplicationUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
    }

Program.cs

 public class Program
{
    public static void Main(string[] args)
    {
        var host = Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webHostBuilder =>
                {
                    webHostBuilder
          .UseContentRoot(Directory.GetCurrentDirectory())
          .UseIISIntegration()
          .UseStartup<Startup>();
                })
                .Build();

        host.Run();
    }
}

1 个答案:

答案 0 :(得分:0)

如错误消息中的链接所述,请更新您的Program类,使其看起来像这样。

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args)
            .Build();

        host.Run();
    }

    // EF Core uses this method at design time to access the DbContext
    public static IHostBuilder CreateHostBuilder(string[] args)
        => Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webHostBuilder =>
                {
                    webHostBuilder
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .UseStartup<Startup>();
                });
}