gpt4 book ai didi

c# - ASP.NET 核心 : Error when using a custom DbContext while also using Identity

转载 作者:行者123 更新时间:2023-12-03 19:34:11 25 4
gpt4 key购买 nike

我已经使用 Entity Framework 基于现有的 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();

}

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

InvalidOperationException: The DbContextOptions passed to the IdentityDbContext constructor must be a DbContextOptions. When registering multiple DbContext types make sure that the constructor for each context type has a DbContextOptions parameter rather than a non-generic DbContextOptions parameter.



我的自定义上下文的构造函数确实有一个参数:
    public CustomDbContext(DbContextOptions<CustomDbContext> options)
: base(options)
{
}

为什么我收到错误?

最佳答案

我有同样的问题。
我的情况是,我需要两个上下文 读取数据上下文 写数据上下文 ,我用底部上下文解决了这个异常

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);
}
}

Pay attention to the DataContext Constructor

 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);
}
}

And for registeration

 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();
});

关于c# - ASP.NET 核心 : Error when using a custom DbContext while also using Identity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com