2015-06-02 111 views
2

我有一個查詢是一個連接到幾個表像TableATableBTableCTableD並在最後我要說的select tableA其TABLEA roecrds工作,它回。 然後後來我有另一個查詢其tables, joins and where clause是完全一樣的第一個查詢,但唯一不同的是,在年底,我這個時候說select tableB組合兩個LINQ查詢,只有他們返回的結果是不同的

所以我的問題是,我可以結合在一起,這些讓我不需要兩次運行查詢?

 var query1 = (from ta in this.Context.TableA 
          join tb in this.Context.TableB on ta.Id equals tb.Id 
          join tc in blah 
          join td in blah 
          join te in blah 
          join tf in blah 
          join tg in blah 
          where (someConditionIsTrueOk) 
          select tg).ToList(); 


     var query2 = (from ta in this.Context.TableA 
          join tb in this.Context.TableB on ta.Id equals tb.Id 
          join tc in blah 
          join td in blah 
          join te in blah 
          join tf in blah 
          join tg in blah 
          where (someConditionIsTrueOk) 
          select te).ToList(); 
+0

可能有助於你看r查詢。如何:'.Select(x => new {x.TableA,x.TableB})' –

+0

@GrantWinney更新,添加示例查詢...使用想像力:D – Bohn

回答

1

您可以選擇多個表,表內或列,並在一起歸入一個匿名類,然後在即時創建:

var result = (from ta in this.Context.TableA 
       join tb in this.Context.TableB on ta.Id equals tb.Id 
       ... 
       ... 
       where (someConditionIsTrueOk) 
       select new {ta, tb}).ToList(); 

var firstTableA = result[0].ta; 
var firstTableB = result[0].tb; 
1

創建一個具有tg,te等的類。

然後查詢只有一次:

var listOfThings = (from ta in this.Context.TableA 
          join tb in this.Context.TableB on ta.Id equals tb.Id 
          join tc in blah 
          join td in blah 
          join te in blah 
          join tf in blah 
          join tg in blah 
          where (someConditionIsTrueOk) 
          select new YourNewClass { Tg = tg, Te = te, and so on }).ToList(); 

或者正如格蘭特說,如果你不需要的結構,你可以選擇一個匿名對象:

var query = (from ta in this.Context.TableA 
      join tb in this.Context.TableB on ta.Id equals tb.Id 
      ... 
      ... 
      where (someConditionIsTrueOk) 
      select new {tg, te}).ToList();