Reputation: 73898
I use EF 4 and C#.
I have a query like:
var contentsAuthor = from c in context.CmsContents
join a in context.CmsAuthors on c.AuthorId equals a.AuthorId
where a.UserId == userGuid
select new
{
c.Title,
c.ContentId
};
I would like rewrite it in Linq with Lambda Expression. My questions:
Notes: probably the title for this question is not appropriate, let me know I will improve it
Thanks guys for your help on this!
Upvotes: 1
Views: 1307
Reputation: 301
var result = context.CmsContents
.Join(context.CmsAuthors.Where(x => x.auth.UserId == userGuid),
content => content.AuthorId,
author => author.AuthorId,
(cont, auth) => new { cont, auth })
.Select(x => new { x.cont.Title, x.cont.ContentId });
Upvotes: 0
Reputation: 364249
The lambda expression should look like:
var contentsAuthor = context.CmsContents
.Join(context.CmsAuthors,
content => content.AuthorId,
author => author.AuthorId,
(content, author) => new { content, author })
.Where(x => x.author.UserId == userGuid)
.Select(x => new { x.content.Title, x.content.ContentId });
Both yours and this version are LINQ queries. This one uses lambdas directly whereas your version uses syntactic sugar available in C#. They are the same. LINQ-to-Entities have nothing to do with this.
Anyway if you are using LINQ-to-Entities your CmsContent
should have Author
property and your query would reduce to:
var contentsAuthor = context.CmsContents
.Where(c => c.Author.UserId == userGuid)
.Select(c => new { c.Title, c.ContentId });
The LINQ-to-Entities provider will make join for you when translating expression tree to SQL query.
Upvotes: 3
Reputation: 12437
Lambda:
var contentsAuthor = context.CmsContents
.Join(context.CmsAuthors, c => c.AuthorId, a => a.AuthorId, (c, a) => new { Contents = c, Author = a })
.Where(w => w.Author.UserId == userGuid)
.Select(s => new { s.Contents.Title, s.Contents.ContentId });
The way you did it is fine though. I call it query syntax, but I'm not sure if it has an official name.
For this sort of stuff, check out LINQPad. In "Expression" mode, you can type a query like you have, and click on the Lambda symbol and it'll show you the lambda version of your query.
Upvotes: 0