asp.net-core - 如何让 IdentityServer 与 AddDbContextPool 一起使用
问题描述
我正在尝试在使用 IdentityServer 进行身份验证的 ASP Core API 项目中利用 AddDBContextPool。问题是,要使用 PersistedGrants,您需要以这种方式设置 DBContext:
private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options)
{
_operationalStoreOptions = operationalStoreOptions;
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
}
AddDBContextPool 只需要一个仅将 DbContextOptions 作为参数的构造函数。所以我不能再注入 operationStoreOptions 了。
我尝试使用 Startup 类中的 AddOperationalStore(),但出现以下错误:
实体类型“DeviceFlowCodes”需要定义一个主键。如果您打算使用无密钥实体类型,请调用“HasNoKey()”。
知道我错过了什么吗?
解决方案
我最终在我的班级中手动实现了 IPersistedGrantDbContext 接口。代码如下,以防万一这可以帮助其他人。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IPersistedGrantDbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
// No tracking needed as all transactions are disconnected
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
}
public DbSet<PersistedGrant> PersistedGrants { get; set; } = null!;
public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; } = null!;
public Task<int> SaveChangesAsync()
{
return base.SaveChangesAsync();
}
protected override void OnModelCreating(ModelBuilder builder)
{
OperationalStoreOptions options = new OperationalStoreOptions
{
DeviceFlowCodes = new TableConfiguration("DeviceCodes"),
PersistedGrants = new TableConfiguration("PersistedGrants")
};
base.OnModelCreating(builder);
builder.ConfigurePersistedGrantContext(options);
// ... Rest of configuration here
}
}
推荐阅读
- ios - ARWorldTrackingConfiguration 与 ARImageTrackingConfiguration
- go - golang.org/x/crypto/ssh 服务器中的多个通道
- rapids - 在 Rapids 0.19 环境(CONDA)的 Pycaret 2.2 中运行比较模型时出错
- python - 如何在 Flask 中显示链接中的图像?
- python - 无法在 python 类中调用函数
- azure-log-analytics - 巧妙地格式化毫秒
- python - 熊猫替换一列中的值基于另一列
- python - 无法让 Flask、Gunicorn 和 Nginx 工作
- vba - 将excel表格分解为文本文件 - 格式化
- excel - 如何留出时间通过 Excel 中的 VBA 从 Bloomberg 刷新 BDH 公式?