ASP.NET Core:使用自定义 DbContext 同时使用 Identity 时出错

hsb*_*sid 7 c# entity-framework asp.net-identity asp.net-core

我使用实体框架基于现有的 Azure SQL 数据库创建了 dbContext。我将此数据库添加到我的应用程序的服务中,如下所示:

        public void ConfigureServices(IServiceCollection services)
    {
        //Identity Database Context
        services.AddDbContext<IdentityDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DataDb"),
            optionsBuilders =>
            optionsBuilders.MigrationsAssembly("WebPortal"))
        );

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<IdentityDbContext>()
            .AddDefaultTokenProviders();

        //Custom Database Context
        services.AddDbContext<CustomDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("CustomDb"))
        );

        services.AddMvc();

    }
Run Code Online (Sandbox Code Playgroud)

当我尝试运行此程序时,我收到以下错误消息:

InvalidOperationException:传递给 IdentityDbContext 构造函数的 DbContextOptions 必须是 DbContextOptions。注册多个 DbContext 类型时,请确保每个上下文类型的构造函数具有 DbContextOptions 参数,而不是非泛型 DbContextOptions 参数。

我的自定义上下文的构造函数确实有一个参数:

    public CustomDbContext(DbContextOptions<CustomDbContext> options)
        : base(options)
    {
    }
Run Code Online (Sandbox Code Playgroud)

为什么我会收到错误消息?

小智 5

我有同样的问题。我的情况是,我需要两个 Context ReadDataContextWriteDataContext,我用底部 Contexts 解决了这个异常

public class ReadOnlyDataContext : DbContext
{
    public ReadOnlyDataContext(DbContextOptions options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.RemovePluralizingTableNameConvention();
        Assembly assemblyWithConfigurations = typeof(TaskConfiguration).Assembly;
        modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意DataContext构造函数

 public class WriteDataContext : DbContext, IContext
{
    public WriteDataContext(DbContextOptions<WriteDataContext> options)
        : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.RemovePluralizingTableNameConvention();
        Assembly assemblyWithConfigurations = typeof(TaskConfiguration).Assembly;
        modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
    }
}
Run Code Online (Sandbox Code Playgroud)

并进行登记

 services.AddDbContext<DataContext>(opt =>
        {
            opt.UseSqlServer(configuration.GetConnectionString("CommanderConnection"));
            opt.LogTo(Console.WriteLine).EnableSensitiveDataLogging();
        });
 services.AddDbContext<ReadOnlyDataContext>(opt =>
        {
            opt.UseSqlServer(configuration.GetConnectionString("CommanderConnection"));
            opt.LogTo(Console.WriteLine).EnableSensitiveDataLogging();
        });
Run Code Online (Sandbox Code Playgroud)