【问题标题】:Is there a way to define common relationship filters in Entity Framework Core?有没有办法在 Entity Framework Core 中定义通用关系过滤器?
【发布时间】:2022-01-14 11:37:13
【问题描述】:

假设我的关系定义为:

public class Report {
  public bool Approved { get; set; }
}

public class FileCabinet {
  public List<Report> Reports { get; set; }
  [NotMapped]
  public IEnumerable<Report> ApprovedReports => Reports.Where(x => x.Approved);
}

ApprovedReports 未映射,不能用于数据库查询,但它会在本地过滤来自数据库的结果。我想以一种可以在 Linq 查询数据库中使用的方式定义过滤器,而不是开发人员必须使用.Where(x =&gt; x.Approved)。有没有办法在 EF Core 中映射此属性或定义过滤器?需要明确的是,这不是全局过滤器。这是一些查询会使用而其他查询不会使用的常见过滤器。

【问题讨论】:

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


    【解决方案1】:

    不在实体本身上,因为它没有对 DbContext 的引用,并且Reports 是一个集合,而不是一个查询。您可以在 DbContext 上放置一个方法

    IQueryable<FileCabinet> FileCabinetWithApprovedReports => this.FileCabinets.Include( f => f.Reports.Where( r => r.Approved) );
    

    您可以向其中编写其他查询表达式。

    或添加Global Query Filter 以使已批准的报告成为默认报告。

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2018-05-18
      相关资源
      最近更新 更多