【问题标题】:EF Core 全局过滤器查询(按 userId)
【发布时间】:2022-01-22 02:40:24
【问题描述】:

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

这种情况下如何进行全局过滤查询。

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

【问题讨论】:

    标签: c# .net entity-framework entity-framework-core


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 2021-08-21
      • 2023-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多