如何使用多个联接聚合和SUM EntityFramework字段

时间:2017-05-09 22:47:34

标签: c# linq linq-to-entities aggregate grouping

我能够产生一组可取的结果,但我需要对这些字段进行分组和总结,并且正在努力理解如何处理这个问题。

在我的场景中,获得结果的最佳方式是:

  1. 有一个独特的[KeyCode](现在我得到很多记录,同样的KeyCode 但不同的职业细节)
  2. SUM工资和投影字段(在同一查询中)
  3. 这是我的LINQ代码:

    private IQueryable<MyAbstractCustomOccupationInfoClass> GetMyAbstractCustomOccupationInfoClass(string[] regionNumbers)
    {
        //Get a list of wage data
        var wages = _db.ProjectionAndWages
            .Join(
                _db.HWOLInformation,
                wages => wages.KeyCode,
                hwol => hwol.KeyCode,
                (wages, hwol) => new { wages, hwol }
            )
            .Where(o => regionNumbers.Contains(o.hwol.LocationID))
            .Where(o => o.wages.areaID.Equals("48"))
            .Where(o => regionNumbers.Contains(o.wages.RegionNumber.Substring(4))); //regions filter, remove first 4 characters (0000)
    
        //Join OccupationInfo table to wage data, for "full" output results
        var occupations = wages.Join(
                    _db.OccupationInfo,
                    o => o.wages.KeyCode,
                    p => p.KeyCode,
                    (p, o) => new MyAbstractCustomOccupationInfoClass
                    {
                        KeyCode = o.KeyCode,
                        KeyTitle = o.KeyTitle,
                        CareerField = o.CareerField,
                        AverageAnnualOpeningsGrowth = p.wages.AverageAnnualOpeningsGrowth,
                        AverageAnnualOpeningsReplacement = p.wages.AverageAnnualOpeningsReplacement,
                        AverageAnnualOpeningsTotal = p.wages.AverageAnnualOpeningsTotal,
                    });
    
        //TO-DO: How to Aggregate and Sum "occupations" list here & make the [KeyCode] Distinct ?
    
        return occupations;
    }
    

    我不确定是否应该在第二次加入时执行分组机制?或者执行.GroupJoin()?或者有第三个查询?

1 个答案:

答案 0 :(得分:1)

var occupations = _db.OccupationInfo.GroupJoin(
            wages,
            o => o.KeyCode,
            p => p.wages.KeyCode,
            (o, pg) => new MyAbstractCustomOccupationInfoClass {
                KeyCode = o.KeyCode,
                KeyTitle = o.KeyTitle,
                CareerField = o.CareerField,
                AverageAnnualOpeningsGrowth = pg.Sum(p => p.wages.AverageAnnualOpeningsGrowth),
                AverageAnnualOpeningsReplacement = pg.Sum(p => p.wages.AverageAnnualOpeningsReplacement),
                AverageAnnualOpeningsTotal = pg.Sum(p => p.wages.AverageAnnualOpeningsTotal),
            });