2014-02-25 61 views
1
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表達式用於上述查詢。在LINQ表達式中嵌套查詢加入

到目前爲止,我曾嘗試:

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) 

但是,這是我想要的結果的一半。

+0

VAR的查詢= db.tb_DeviceLog.Join(db.tb_DeviceLog,DL => DL.inventoryLogId,DL1 => DL1.inventoryLogId,(DL,DL1)=>新DL1.inventoryLogId,DL1.trackedOn.Value})。GroupBy(a => a.inventoryLogId) 但是,這是我想要的結果的一半。此外,我無法使用此表達式獲取TrackedOn(日期字段)的最大值。 –

回答

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(); 
+0

謝謝你。它效果很好。 正是我想要的。 –