【问题标题】:Find maximum value of all properties in list of objects查找对象列表中所有属性的最大值
【发布时间】:2019-09-14 05:38:03
【问题描述】:

我有以下 Entity Framework Core 查询:

  IQueryable<Product> products = context.Products;

  var maximums = new MaximumModel {
    PA = await products.MaxAsync(x => x.Composition.PA)
    PB = await products.MaxAsync(x => x.Composition.PB)
    PC = await products.MaxAsync(x => x.Composition.PC)
    PD = await products.MaxAsync(x => x.Composition.PD)
    // Other 36 properties ...
  }

这会执行 40 个查询,每个查询一个 ...

有没有办法只执行一个查询?

【问题讨论】:

    标签: entity-framework entity-framework-core linq-to-entities


    【解决方案1】:

    我尚未使用 EF 异步版本对此进行测试,但 LINQ to SQL 解决方案是使用来自 GroupBy 的单例组将查询组合成一个查询:

    var maximums = await products.GroupBy(p => 1)
                                 .Select(pg => new MaximumModel {
                                                    PA = pg.Max(x => x.Composition.PA),
                                                    PB = pg.Max(x => x.Composition.PB),
                                                    PC = pg.Max(x => x.Composition.PC),
                                                    PD = pg.Max(x => x.Composition.PD),
                                                      // Other 36 properties ...
                                 }).FirstAsync();
    

    【讨论】:

    • 确认这适用于 EF 和 EF Core 以及异步风格。一个有趣的方法值得注意的未来。 :)
    猜你喜欢
    • 2018-07-09
    • 2017-06-29
    • 2014-05-07
    • 1970-01-01
    • 2022-07-08
    • 2016-11-07
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多