2008-12-06 44 views
9

我正在嘗試使用lambda表達式在Linq中執行JOIN ...並遇到一些問題。如何使用lambdas和表達式樹在Linq中進行聯接?

我有兩個實體,評論和CommentSources。 CommentSources與評論相關聯。我有以下的代碼,它不工作:

01 IQueryable<Data.Comment> query = ctx.DataContext.Comments; 
02 
03 
04 if (criteria.IsDeleted == DeletedFilter.Deleted) 
05 query = query.Where(row => row.DeletedBy != Guid.Empty); 
06 else if (criteria.IsDeleted == DeletedFilter.NotDeleted) 
07 query = query.Where(row => row.DeletedBy == Guid.Empty); 
08 
09 var data = query.Select(row => CommentInfo.FetchCommentInfo(row)); 

我需要加入CommentSources在場上的評論,我想用,如果可能的話,是這樣的:

01 query = query.Join(join code goes here) 

哪有我在表達式樹中使用lambda表達式來做到這一點?

還有一件事......我如何添加一個Where語句給Join語句?

而不是問另一個問題......我將如何做一個該加入的Where子句?例如,我在CommentSource上有一個名爲SourceId的字段,我想過濾它。

回答

15

你需要指定的五件事(至少):

  • 「外」 序列(評論)(這是隱含的第一個參數)
  • 「內部」 序列(CommentSource)
  • 如何從CommentSource得到一個關鍵
  • 如何從一個註釋來獲得一個關鍵
  • 你想要的結果是什麼成爲一個CommentSource /評論對

例如:

query = query.Join(ctx.DataContext.CommentSource, 
        comment => comment.CommentSourceId, 
        commentSource => commentSource.Id, 
        (comment, commentSource) 
         => new { Comment=comment, CommentSource=commentSource }); 
+1

我要接受這個作爲答案...但想看看你是否可以在點我正確的方向爲連接表添加一個連接語句的位置。 – mattruma 2008-12-06 15:07:31

5

這是我的最終代碼:

  var query = ctx.DataContext.Comments.Join(ctx.DataContext.CommentSources, 
        c => c.CommentId, 
        s => s.CommentId, 
        (c, s) => new {Comment = c, CommentSource = s}); 

      if (criteria.SourceId != null && criteria.SourceId != Guid.Empty) 
       query = query.Where(row => row.CommentSource.SourceId == criteria.SourceId); 

      if (criteria.IsDeleted == DeletedFilter.Deleted) 
       query = query.Where(row => row.Comment.DeletedBy != Guid.Empty); 
      else if (criteria.IsDeleted == DeletedFilter.NotDeleted) 
       query = query.Where(row => row.Comment.DeletedBy == Guid.Empty); 

      var data = query.Select(row => CommentInfo.FetchCommentInfo(row.Comment));