尝试从IdentityContext派生应用程序数据库上下文时出错

时间:2019-06-10 19:11:57

标签: c# asp.net-core entity-framework-core

我正在尝试从IdentityContext派生应用程序上下文,以便在检索数据时只能使用一个上下文。

以下是IdentityContext的定义方式:

public class IdentityContext : IdentityDbContext<ApplicationUser, ApplicationRole, int> {}

这是应用程序上下文:

public partial class MyDbContext : IdentityContext
{
        //

        public MyDbContext(DbContextOptions<MyDbContext> options)
    : base(options)
        { }
        //
}

编译器抱怨options变量:

Error   CS1503  Argument 1: cannot convert from 'Microsoft.EntityFrameworkCore.DbContextOptions<Application.Data.MyDbContext>' to 'Microsoft.EntityFrameworkCore.DbContextOptions<Application.Data.IdentityContext>'    

如果我使用:

public MyDbContext(DbContextOptions<IdentityContext> options)
    : base(options)
        { }

相反,运行迁移时出现错误:

λ dotnet ef migrations add InitialCreate

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

并且:

λ dotnet ef migrations add InitialCreate --context MyDbContext

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[Application.Data.IdentityContext]' while attempting to activate 'Application.Data.MyDbContext'.

在Startup.cs中,我有:

 services.AddDbContext<MyDbContext>(
                    options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))
                );
            services.AddIdentity<ApplicationUser, ApplicationBlogRole>().AddEntityFrameworkStores<MyDbContext>()
                .AddDefaultTokenProviders().AddSignInManager<ApplicationSignInManager>();

1 个答案:

答案 0 :(得分:2)

  

错误CS1503参数1:无法从“ Microsoft.EntityFrameworkCore.DbContextOptions”转换为“ Microsoft.EntityFrameworkCore.DbContextOptions”

根据此错误信息,我猜您的IdentityContext类具有一个接受DbContextOptions<IdentityContext> options参数的构造函数,如下所示:

public class IdentityContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
    public IdentityContext(DbContextOptions<IdentityContext> options) : base(options) 
    { }

    // ...
}

因此它会抱怨您是否在派生上下文中调用base(options)

public partial class MyDbContext : IdentityContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    { }

}

如何解决

更改IdentityContext的构造函数以接收 DbContextOptions options ,并使MyDbContext的构造函数接受 DbContextOptions<MyDbContext> options < / strong>:

public class IdentityContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
    public IdentityContext(DbContextOptions options) : base(options)
    {
    }
}

public partial class MyDbContext : IdentityContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    { }

}

作为旁注,您将添加角色服务为ApplicationBlogRole而不是ApplicationRole的身份服务:

services.AddIdentity<ApplicationUser, ApplicationBlogRole>()  // it might cause problems in future.

也许应该是:

services.AddIdentity<ApplicationUser, ApplicationRole>()