我正在尝试使用lambda表达式在Linq中进行连接...并遇到一些问题.
我有两个实体,评论和评论源.CommentSources与评论相关联.我有以下代码,它确实有效:
01 IQueryablequery = 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语句中添加Where?
而不是问另一个问题......我如何在Join上做Where子句?例如,我在CommentSource上有一个名为SourceId的字段,我想过滤它.
你需要指定五件事(至少):
"外部"序列(注释)(这是隐含的第一个参数)
"内部"序列(CommentSource)
如何从CommentSource获取密钥
如何从评论到密钥
你想要的结果是CommentSource/Comment对
例如:
query = query.Join(ctx.DataContext.CommentSource, comment => comment.CommentSourceId, commentSource => commentSource.Id, (comment, commentSource) => new { Comment=comment, CommentSource=commentSource });
这是我的最终代码:
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));