如何使用lambdas和表达式树在Linq中进行连接?

时间:2008-12-06 14:19:36

标签: .net linq-to-sql

我正在尝试使用lambda表达式在Linq中进行JOIN ...并遇到一些问题。

我有两个实体,评论和评论源。 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)

如何在表达式树中使用lambdas执行此操作?

还有一件事......如何添加Join语句的位置?

而不是问另一个问题......我如何在Join上做Where子句?例如,我在CommentSource上有一个名为SourceId的字段,我想过滤它。

2 个答案:

答案 0 :(得分:15)

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

  • “外部”序列(注释)(这是隐含的第一个参数)
  • “内部”序列(CommentSource)
  • 如何从CommentSource转到密钥
  • 如何从评论中获取密钥
  • 您希望结果为CommentSource / Comment对

例如:

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

答案 1 :(得分: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));