使用Join in LINQ表达式的嵌套查询

时间:2014-02-25 13:16:47

标签: linq

select DL.lat,
       DL.lng,
       DL.speed,
       DL.trackedOn, 
       IL.speedLimit,
       IL.deviceName, 
       IL.deviceId,
       isnull(DeviceIcon, 'Content/images/beach-car.png') as DeviceIcon 
from tb_DeviceLog DL 
inner join (select inventoryLogId, max(trackedOn) as MaxDate
            from tb_DeviceLog
            group by inventoryLogId) IDL 
    on DL.inventoryLogId = IDL.inventoryLogId and Dl.trackedOn = IDL.MaxDate 
inner join tb_InventoryLog IL 
    on DL.inventorylogid = IL.id
inner join tb_Logins LGN 
    on LGN.customers_id = IL.assignedToCustId 
where LGN.userName='cadmin' 

我需要一个用于上述查询的lambda表达式。

到目前为止,我已经尝试过:

var query = db.tb_DeviceLog.Join(db.tb_DeviceLog, DL=>DL.inventoryLogId, DL1=>DL1.inventoryLogId, (DL,DL1)=> new{ DL1.inventoryLogId, DL1.trackedOn.Value}).GroupBy(a=>a.inventoryLogId) 

但这是我想要的结果的一半。

1 个答案:

答案 0 :(得分:0)

几乎很复杂,我喜欢......

你需要这个:

var dbContext = new TestEntities();
        dbContext.tb_DeviceLog
            .Join(dbContext.tb_DeviceLog
                    .GroupBy(u => u.inventoryLogId)
                    .Select(u => new { inventoryLogId = u.Key, MaxDate = u.Max(t => t.trackedOn)}),
                u => new { inventoryLogId = u.inventoryLogId, date = u.trackedOn},
                u => new { inventoryLogId = u.inventoryLogId, date = u.MaxDate},
                (DL , IDL) => new {DL, IDL})
            .Join(dbContext.tb_InventoryLog,
                u => u.DL.inventoryLogId,
                u => u.id
                (u, IL) => new { u.DL, u.IDL, IL })
            .Join(dbContext.tb_Logins,
                u => u.IL.assignedToCustId,
                u => u.customers_id
                (u, LGN) => new { u.DL, u.IDL, u.IL, LGN })
            .Where(u => u.LGN.userName == "cadmin")
            .Select(u => new
            {
                u.DL.lat,
                u.DL.lng,
                u.DL.speed,
                u.DL.trackedOn, 
                u.IL.speedLimit,
                u.IL.deviceName, 
                u.IL.deviceId,

                // i don't know exactly, which table is containing this 'DeviceIcon', probably DL
                u.DL.DeviceIcon == null ? "Content/images/beach-car.png" : u.DL.DeviceIcon
            })
            .ToList();