2012-05-02 101 views
0

用戶:如何一次使用linq to sql連接多個表?

userid name  email 
    1  venkat [email protected] 
    2  venu  [email protected] 
    3  raghu [email protected] 

合作伙伴:

id userid partnerid status 
    1  1  2   1 
    2  1  3   1 

位置:

id userid lat lon 
    1  1  12.00 13.00 
    2  2  14.00 12.00 
    3  3  14.00 14.23 

查詢:

var result = from partner in Partners 
       join user in Users on partner.UserId equals user.PartnerId 
       join location in Locations on patner.UserId equals location.PartnerId 
       where partner.UserId == 1 
       select new { PartnerId = partner.PartnerId, PartnerName = user.Name, Lat = location.Lat, Lon = location.Lon }; 

通過傳遞userid=1作爲參數,我得到這個結果:

partnerid patnername  lat   lon 
    2   venkat   14.00   12.00 
    3   venkat   14.00   14.23 

通過上述結果的觀察這裏partnernames是錯誤的partnerid = 2 - patnamevenu但顯示 「venkat」

partnerid = 3,合作伙伴名稱爲raghu,但顯示venkat

如何顯示正確的合作伙伴名稱?

回答

1

我相信這JOIN這裏是錯誤的:

var result = from partner in Partners 
      join user in Users on user.UserId equals partner.PartnerId 

你用他PartnerID加入用戶自己userId給合作伙伴。

在這兩種情況下,您是否需要將用戶加入到使用PartnerID的合作伙伴?類似這樣的:

var result = from partner in Partners 
      join user in Users on user.PartnerId equals partner.PartnerId