我正在尝试使用。net 5构建多租户应用程序;EF Core和我想设置全局查询过滤器,以便在任何查询中始终包含TenantId过滤器
我尝试了很多方法并遵循文档,但问题是EF缓存了第一个过滤器,并且在TenantId更改时没有更新
我写了下面的代码来模拟每次请求改变TenantId:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Account>().HasQueryFilter(x => x.TenantId == TenantId);
}
public int TenantId => DateTime.Now.Second;
当我跟踪执行的查询时,TenantId总是相同的
您需要更新 tenantId
比较from x => x.TenantId == _tenantId
to x => EF.Property<int>(x, "TenantId") == _tenantId
public class MyAppContext : DbContext
{
private readonly int _tenantId;
public MyAppContext (int tenantId)
{
_tenantId = tenantId;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//If your tenantId comparision is as following, then tenantId will not updated
//modelBuilder.Entity<Account>().HasQueryFilter(x => x.TenantId == _tenantId);
//If your tenantId comparision is as following,
//then tenantId will updated every query excecution
modelBuilder.Entity<Account>()
.HasQueryFilter(x => EF.Property<int>(x, "TenantId") == _tenantId);
}
}