2013-05-28 31 views
5

我使用Csharp的LINQ到創建以下報告使用具有聯接使用兩個地方兩個表

LINQ我有兩個表如下

 

#Users 
nid  pid  name 
1  1  name1 
2  1  name2 

#Transactions 
nid  tid  location dcode 
1  T1  L1   D1 
2  T1  L2   D1 
2  T2  L1   D1 
2  T2  L3   D1 

該報告包含

 

    a) columns from users table where nid != pid 
    b) columns from transactions where tid == T2 and nid = results from a) 
    c) the combination can have only one top row in result 

nid  name  tid  Location 
2  name2  T2  L1 

the second record will not be present 
- 2  name2  T2  L3 

我試過以下,使用加入

var report = (from u in users where u.nid != u.pid 
         join t in transactions 
         where t.tid == "T2" 
         on u.nid equals t.nid 
         select new 
         { 
         // the report columns 
         }).Distinct().ToList(); 

在第二顯示

一個錯誤「其中」

謝謝你的任何援助

回答

2

交換過濾和查詢的接合部和重命名tidt.tid或其他期望的過濾條款(在你的例子所得的表幹有交易與tid == "T1",但你嘗試用T2進行篩選):

var report = (from u in users  
       join t in transactions 
       on u.nid equals t.tid  //<-- this line should precede 
       where t.tid == "T2"  //<-- this one 
       && u.nid != u.pid 
       select new 
       { 
        // the report columns 
       }).Distinct().ToList(); 

加入部分不能分開,所以你不能寫where,直到你完成joinon子句。

+0

是的,錯誤已經消失,我會在8分鐘後將其標記爲答案..再次感謝 – arvind