GroupJoin使用Linq for Entities lambda在连接表上进行顶级选择

时间:2016-07-04 21:58:19

标签: c# sql-server entity-framework linq lambda

我有一个表有多个>很多关系的表,尽管在数据库模式中没有这样的分类。

我有以下SQL,我想用等效的lambdas复制。

SELECT S1.ServiceId, S1.ServiceDate, S1.TrainNumber, S1.SourceMessageRef, 

S2.SourceMessageRef, S1.Created, S2.Created, S1.vehicles, S1.grossWeight, S1.NettWeight, S1.Tare, S1.Nominal, S2.ConsignmentNoteNum, S2.NumOfWagons, S2.GrossWeight, S2.NettWeight, S2.NominalTonnes
FROM (select c.ServiceId, c.ServiceDate, c.TrainNumber, c.SourceMessageRef, c.Created, COUNT(1) as vehicles, SUM(c.GrossWeight) AS GrossWeight, SUM(c.NettWeight) as NettWeight, sum(c.TareWeight) as Tare, sum(c.NominalWeight) as Nominal
        from [Staging].[Consists] c
        GROUP BY [ServiceId],[ServiceDate],[TrainNumber],[SourceMessageRef],[Created]
        ) AS S1
LEFT OUTER JOIN (SELECT c.Created, c.SourceMessageRef, c.ServiceId, 
                        c.ServiceDate, c.ConsignmentNoteNum, c.GrossWeight, 
                        c.NettWeight, c.NominalTonnes, c.NumOfWagons,
                        row_number() over (partition by c.ServiceId, c.ServiceDate order by c.Created DESC) as rn
                   FROM [Staging].[Consignment] c ) S2 
        ON S2.ServiceId = S1.ServiceId AND S2.ServiceDate = S1.ServiceDate AND S2.rn = 1
ORDER BY S2.ServiceDate DESC, S1.Created DESC, S2.SourceMessageRef DESC, S1.SourceMessageRef DESC

到目前为止,我能做到的最好的是:

    var consists = db.Consists
        .GroupBy(c => new { c.ServiceId, c.ServiceDate, c.SourceMessageRef })
        .GroupJoin(db.Consignments,
            a => new { a.Key.ServiceId, a.Key.ServiceDate },
            b => new { b.ServiceId, b.ServiceDate },
            (a, b) => new ConsistOverviewDto() 
                {
                    ServiceId = a.Key.ServiceId,
                    ServiceDate = a.Key.ServiceDate,
                    TrainNumber = a.FirstOrDefault().TrainNumber,
                    ConsistVehicleCount = a.Count(),
                    ConsistGrossWeight = a.Sum(a1 => a1.GrossWeight ?? 0m),
                    ConsistNettWeight = a.Sum(a1 => a1.NettWeight ?? 0m),
                    ConsistTareWeight = a.Sum(a1 => a1.TareWeight ?? 0m),
                    ConsistNominalWeight = a.Sum(a1 => a1.NominalWeight ?? 0),

                    ConsignmentVehicleCount = b.Count(),
                    ConsignmentGrossWeight = b.Sum(b1 => b1.GrossWeight ?? 0m),
                    ConsigmentNettWeight = b.Sum(b1 => b1.NettWeight ?? 0m),
                    ConsignmentNominalWeight = b.Sum(b1 => b1.NominalTonnes ?? 0)
                })
        .OrderByDescending(c => c.ServiceDate);

这似乎并不是非常接近,特别是只想匹配第一个外连接条目(如果存在)的概念。

有人可以协助演示实现与附加SQL类似的功能所需的lambda。

0 个答案:

没有答案