gpt4 book ai didi

entity-framework - Entity Framework Core 全局动态查询过滤器

转载 作者:行者123 更新时间:2023-12-03 08:21:02 26 4
gpt4 key购买 nike

我们正在使用 ef core 3.1我们想使用动态查询过滤器,我尝试了示例实现,但没有像我们预期的那样正常工作,过滤始终相同的租户 ID,我尝试在下面进行解释


public class TestDbContext : DbContext
{

public DbSet<TenantUser> TenantUsers { get; set; }


private readonly ITenantProvider _tenantProvider;

private Guid? TenantId => _tenantProvider.TenantId;

public TestDbContext (DbContextOptions<TestDbContext > options, ITenantProvider tenantProvider) : base(options)
{
_tenantProvider = tenantProvider;
}


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TenantUser>()
.HasQueryFilter(p => EF.Property<Guid>(p, "TenantId") == TenantId);
}

}

ITenantProvider 从 HttpContext header 返回 TenantId

此代码始终从第一个请求中过滤相同的租户 ID

更新:


public class TenantProvider : ITenantProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;

public TenantProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

public Guid? TenantId
{
get
{
if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue(HeaderNames.TenantId, out var tenantId) &&
Guid.TryParse(tenantId, out Guid parsedTenantId))
{
return parsedTenantId;
}
return null;
}
}
}

例如第一个请求 TenantId = 60000000-0000-0000-0000-000000000000此过滤器 => 60000000-0000-0000-0000-000000000000

第二个请求 TenantId = 10000000-0000-0000-0000-000000000000此过滤器 => 60000000-0000-0000-0000-000000000000

最佳答案

您还应该实现自定义 IModelCacheKeyFactory

public class MyModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
if (context is TestDbContext testDbContext)
{
return (context.GetType(), testDbContext.TenantId);
}
return context.GetType();
}
}

然后,你需要像这样替换

var builder = new DbContextOptionsBuilder<TestDbContext>();

builder.ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory>();

var context = new TestDbContext(builder.Options);

引用: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.imodelcachekeyfactory

关于entity-framework - Entity Framework Core 全局动态查询过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67820361/

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