2014-03-25 25 views
1

我在LINQ中執行左連接,並且遇到問題。我的問題是我在我的where子句中對兩個表進行比較,但我實際上無法訪問'cat'表。我如何去訪問左連接中的表格?無法訪問LINQ中的左連接實體

var query = from apple in Apple 
      join ball in Ball on apple.Id equals ball.AppleId 
      join cat in Cat on ball.Id equals cat.BallId into leftJoin 
      join dog in Dog on ball.Id equals dog.BallId 
      where apple.Id == 5 

      // At this point cat is not accessable. Cannot resolve symbol "cat". 
      where dog.CatName == cat.Name 

      from cat in leftJoin.DefaultIfEmpty() 
      select new 
      { 
       // select stuff here... 
      }; 

回答

1

我不是100%肯定,但試試這個:

var query = from apple in Apple 
      join ball in Ball on apple.Id equals ball.AppleId 
      join cat in Cat on ball.Id equals cat.BallId into leftJoin 
      from cat in leftJoin.DefaultIfEmpty() 
      join dog in Dog on ball.Id equals dog.BallId 
      where apple.Id == 5 
      where dog.CatName == cat.Name 
      select new 
      { 
       // select stuff here... 
      }; 

當然,如果您設置導航屬性適當,這將看起來有點像這樣:

var query = from apple in Apple 
      from ball in apple.Balls 
      from cat in ball.Cats.DefaultIfEmpty() 
      from dog in ball.Dogs 
      where apple.Id == 5 
      where dog.CatName == cat.Name 
      select new 
      { 
       // select stuff here... 
      }; 
+0

工作。我需要在where子句之前的DefaultIfEmpty()方法。謝謝! – Halcyon

0

問題是,你已經選擇了多個貓進入一個LeftJoin ...這使得它是一個IEnumerable,所以沒有一個單一的貓,所以查詢不完全有意義...你想檢查,如果狗匹配任何那些加入的貓?

我已將您的leftJoin更名爲catsForThisBall以使其更清晰。

var query = from apple in Apple 
      join ball in Ball on apple.Id equals ball.AppleId 
      join cat in Cat on ball.Id equals cat.BallId into catsForThisBall 
      join dog in Dog on ball.Id equals dog.BallId 
      where apple.Id == 5 

      // catsForThisBall is IEnumerable<Cat>... cat doesn't exist. 
      where catsForThisBall.Any(c => c.name == dog.name) 

      select new 
      { 
       // select stuff here... 
      };