I'm trying to do a JOIN in Linq using lambda expressions ... and running into some problems.
I have two entities, Comments and CommentSources. CommentSources are associated to Comments. I have the following code, which does work:
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));
I need to join CommentSources on Comments on the field, and I would like to use, if possible, something like:
01 query = query.Join(join code goes here)
How can I do this using lambdas in the expression tree?
One more thing ... how do I add a Where to the Join statement?
Instead of asking another question ... how would I do a Where clause on that Join? For example, I have a field called SourceId on the CommentSource that I would like to filter by.
In a LINQ query expression, join operations are performed on object collections. Object collections cannot be "joined" in exactly the same way as two relational tables. In LINQ, explicit join clauses are only required when two source sequences are not tied by any relationship.
So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.
You need to specify five things (at least):
For example:
query = query.Join(ctx.DataContext.CommentSource,
comment => comment.CommentSourceId,
commentSource => commentSource.Id,
(comment, commentSource)
=> new { Comment=comment, CommentSource=commentSource });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With