EF Core 全局过滤器查询通过 userId

EF Core global filter query by userId

我有这样的情况,我想通过登录的用户 ID 或确切地说是某个名为 AllowedVehicles 的字段来过滤表。 问题是 identityContext 仅在登录时填充字段 AllowedVehicles,之后 AllowedVehicles 属性 实际从数据库中读取。我的代码不起作用,因为 AllowedVehicles 是空列表,一旦 OnModelCreating 被执行并且它 只执行一次 .

在这种情况下如何进行全局筛选查询。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyGlobalFilters<IBaseEntity>(x => x.DeletedAt == null);
    if (_identityContext != null && _identityContext.AllowedVehicles.Count() > 0)
    {
        modelBuilder.ApplyGlobalFilters<Vehicle>(x => _identityContext.AllowedVehicles.Select(x => x.Id).Contains(x.Id));
    }
}

OnModelCreating 每个 DbContext class 只调用一次。而且您不必期望可以有条件地应用过滤器。

一种解决方案是在过滤器中定义您的条件:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyGlobalFilters<IBaseEntity>(x => x.DeletedAt == null);

    modelBuilder.ApplyGlobalFilters<Vehicle>(x => _identityContext == null 
        || !_identityContext.AllowedVehicles.Any() 
        || _identityContext.AllowedVehicles.Select(x => x.Id).Contains(x.Id)
    );
}