2014-03-25 88 views
1

我最近遇到了一些SQL代碼,看起來像這樣取與在連接條件使用LINQ

SELECT 
    a.Id, 
    b.Id, 
    c.Id, 
    d.Id, 
    b.Name, 
    d.Occupation, 
FROM TableA a 
JOIN TableB b ON a.Id = b.Id 
JOIN TableC c ON b.Id = c.Id AND b.Name = a.Name 
JOIN tableD d ON c.Id = d.Id AND c.Occupation = d.Occupation 

我從來沒有使用AND將裏面相應的LINQ查詢連接像這樣(的情況下,我用的是實體框架和LINQ爲我的所有查詢)。我通常把我所有的與運算裏面有where子句是這樣的:

var query = from a in dbContext.TableA 
      join b in dbContext.TableB on a.Id equals b.Id 
      join c in dbContext.TableC on b.Id equals c.Id 
      join d in dbContext.TableD on c.Id equals d.Id 
      where b.Name = a.Name 
      where c.Occupation = d.Occupation 
      select new 
      { 
       AId = a.Id, 
       BId = b.Id, 
       CId = c.Id, 
       DId = d.Id, 
       BName = b.Name, 
       DOccupation = d.Occupation, 
      }; 

我可以使用哪些技術來得到我的LINQ查詢匹配上面的SQL語句?

回答

1

你可以從你的屬性構建匿名類型,像這樣對多個屬性加入:

var query = from a in dbContext.TableA 
      join b in dbContext.TableB on new { a.Id, a.Name } equals new { b.Id, b.Name } 
      join c in dbContext.TableC on b.Id equals c.Id 
      join d in dbContext.TableD on new { c.Id, c.Occupation } equals new { d.Id, d.Occupation } 
      select new 
      { 
       AId = a.Id, 
       BId = b.Id, 
       CId = c.Id, 
       DId = d.Id, 
       BName = b.Name, 
       DOccupation = d.Occupation, 
      }; 

注意,名稱,訂單,並在匿名類型的每個屬性的數據類型必須是在兩個相同爲了這個工作,equals的兩側。否則,它們將是兩種不同的匿名類型,並且不會相等。

+0

這正是我所期待的。謝謝! – Halcyon