2008-12-06 45 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));