2013-06-06 59 views
1

這段代碼工作正常,但我想知道是否沒有辦法將它寫入一個LINQ表達式中,所以數據庫服務器可以完成一次傳遞,而不是實現一個結果集,然後循環通過它,這是我的代碼將產生。尋找與LINQ的界限

var logs = from AssetLog log in dc.AssetLogs 
      where log.AssetId == assetId && log.Recorded >= start && log.Recorded <= finish 
      select log; 
    return new GetInteractionBoundsResult() 
    { 
    N = logs.Max(log => log.Latitude), 
    S = logs.Min(log => log.Latitude), 
    W = logs.Min(log => log.Longitude), 
    E = logs.Max(log => log.Longitude) 
    }; 

所以,LINQ大師,你會怎麼寫上面,使其產生在數據庫或多或少這樣的:

SELECT MIN(Latitude) S, MAX(Latitude) N, MIN(Longitude) W, MAX(Longitude) E 
FROM ASSETLOG WHERE etc etc 

回答

1

當然,只是欺騙你的LINQ提供程序,以爲它仍然有工作查詢到了最後:

var logs = from asset in dc.Assets 
      where asset.AssetId == assetId 
      let g = asset.AssetLogs 
       .Where(log => log.Recorded >= start && log.Recorded <= finish) 
      select new GetInteractionBoundsResult 
       { 
        N = g.Max(log => log.Latitude), 
        S = g.Min(log => log.Latitude), 
        W = g.Min(log => log.Longitude), 
        E = g.Max(log => log.Longitude) 
       }; 
    return logs.Single(); 

一個GROUP BY可能有更好的表現比加入,上面的查詢會產生:

var logs = from log in dc.AssetLogs 
      where log.AssetId == assetId && 
       log.Recorded >= start && log.Recorded <= finish 
      group log by log.AssetId into g 
      select new GetInteractionBoundsResult 
       { 
        N = g.Max(log => log.Latitude), 
        S = g.Min(log => log.Latitude), 
        W = g.Min(log => log.Longitude), 
        E = g.Max(log => log.Longitude) 
       }; 
    return logs.Single(); 
+0

我敢肯定'logs'將無法引用自身。 – dahlbyk

+0

@dahlbyk:有幾個錯別字,對不起。 – StriplingWarrior

+0

groupby成,應該想到的,謝謝 –

0

這將需要一個相當複雜的LINQ提供程序,但子查詢可能工作:

var res = from asset in dc.Assets 
      where log.AssetId == assetId 
      let logs = (from AssetLog log in asset.AssetLogs 
         where log.Recorded >= start && log.Recorded <= finish 
         select log) 
      select new GetInteractionBoundsResult() 
      { 
       N = logs.Max(log => log.Latitude), 
       S = logs.Min(log => log.Latitude), 
       W = logs.Min(log => log.Longitude), 
       E = logs.Max(log => log.Longitude) 
      }; 
    return res.Single(); 
+0

它*是一個非常複雜的提供者:Linq2Sql。也謝謝你。 groupby是我想要考慮的。 –