Converting query expression to Linq method syntax
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:
- How to rewrite it?
- What is the appropriate name for my query syntax and the new with Linq and Lambda (query expression and Linq to Entities???). Please give me a hit on this point I'm confused.
Notes: probably the title for this question is not appropriate, let me know I will improve it
Thanks guys for your help on this!
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.
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.
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 });
精彩评论