2011-02-09 37 views
2

我有以下部分Linq查詢:Linq - 如何構建不含'join'關鍵字的查詢?

var query = from ri in RouteInstance 
     join rir in RouteInstanceRules on ri.RouteInstanceID equals rir.RouteInstanceID 
     join rl in RoutingLocation on rir.RoutingLocationID equals rl.RoutingLocationID 
     join rlh in RoutingLocationHistory on rl.RoutingLocationID equals rlh.RoutingLocationID 
     where rlh.RouteTakenTime >= new System.DateTime(2011,2,4) && rlh.RouteTakenTime <= new System.DateTime(2011,2,5) 

There is a 1:M relationship between RouteInstance and RouteInstanceRules 
There is a 1:M relationship between RouteInstanceRules and RoutingLocation 
There is a 1:M relationship between RoutingLocation and RoutingLocationHistory 

由於這些關係使用FKS執行,因此已知L2S,我應該能夠構造此查詢,而無需使用「加入」的關鍵字。但是,我很難理解如何去做。

謝謝。

+0

這是你在找什麼? http://blogs.msdn.com/b/charlie/archive/2007/02/20/one-to-many-and-joins.aspx從這篇文章http://stackoverflow.com/questions/4133455/linq-加入混亂。看起來你已經在那裏發表評論。 – Chris 2011-02-09 14:09:36

+0

@Chris--我不認爲這是完全一樣的,我對我發佈的問題的答案並不滿意。但是,謝謝。 – 2011-02-09 14:22:49

回答

2

你到底想要的RouteInstances?如果是這樣的話:

var query = DataContext.RoutingLocationHistory 
      .Where(rlh => rlh.RouteTakenTime >= new System.DateTime(2011,2,4) 
         && rlh.RouteTakenTime <= new System.DateTime(2011,2,5)) 
      .Select(rlh => rlh.RoutingLocation.RouteInstanceRule.RouteInstance) 
      .Distinct(); 
1

我測試的情景像你這樣的,並得到了相同的結果
你可以選擇很多沒有加入,某事像:

var query = from ri in RouteInstance 
      from rir in RouteInstanceRules 
      from rl in  RoutingLocation 
      from rlh in RoutingLocationHistory 
      where ri.RouteInstanceID == rir.RouteInstanceID && 
      rir.RoutingLocationID == rl.RoutingLocationID && 
      rl.RoutingLocationID == rlh.RoutingLocationID && 
      rlh.RouteTakenTime >= new System.DateTime(2011,2,4) && rlh.RouteTakenTime <= new System.DateTime(2011,2,5) 
0

檢查dbml設計器中的關聯。如果它注意到你的外鍵,它會自動創建關聯。如果沒有 - 您可以自己添加它們(即使外鍵不存在或未被強制執行)。

通過查詢關聯屬性,您可以隱藏您的關係詳情。

query = 
    from ri in dataContext.RouteInstances 
    from rir in ri.RouteInstanceRules 
    from rl in rir.RoutingLocations 
    from rlh in rl.RoutingLocationHistories 
    where rlh.RouteTakenTime >= new System.DateTime(2011,2,4) 
    && rlh.RouteTakenTime <= new System.DateTime(2011,2,5) 

如果你想similiar結果Guillaume86的答案,但沒有明顯的......然後做這個subquery'ing過濾器。

IQueryable<RouteInstance> query = 
    from ri in dataContext.RouteInstances 
    where ri.RouteInstanceRules 
    .Any(rir => rir.RoutingLocations 
     .Any(rl => rl.RoutingLocationHistories 
     .Any(rlh => rlh.RouteTakenTime >= new System.DateTime(2011,2,4) 
      && rlh.RouteTakenTime <= new System.DateTime(2011,2,5) 
     ) 
     ) 
    ) 
    select ri;