GibboK
GibboK

Reputation: 73988

How to convert a LINQ query from query syntax to query method

Linq and EF4.

I have this Linq query in query syntax I would like convert into query method.

Are you able to do it? I tried more tha 2 hours without success :-(

Thanks for your time

CmsContent myContentObj = (from cnt in context.CmsContents
                   from categoy in cnt.CmsCategories
                   where categoy.CategoryId == myCurrentCategoryId && cnt.ContentId == myCurrentContentId
                   select cnt).Single();

Upvotes: 1

Views: 347

Answers (3)

Jeff Mercado
Jeff Mercado

Reputation: 134571

My original answer selected the wrong item. It's a bit more complicated than what I had (which Ani has posted). Here's what I believe is an equivalent query however and should perform better:

CmsContent myContentObj =
    context.CmsContents
           .Where(cnt => cnt.ContentId == myCurrentId
                      && cnt.CmsCategories
                            .Any(categoy => categoy.CategoryId == myCurrentCategoryId))
           .Single();

Upvotes: 2

Ani
Ani

Reputation: 113462

Here's how the C# compiler actually does it, with some help from .NET Reflector to verify:

var myContentObj = context
                   .CmsContents  
                   .SelectMany(cnt => cnt.CmsCategories,
                               (cnt, categoy) => new { cnt, categoy })
                   .Where(a => a.categoy.CategoryId == myCurrentCategoryId
                            && a.cnt.ContentId == myCurrentContentId)
                   .Select(a => a.cnt)
                   .Single();

Essentially, the 'nested' from clauses results in a SelectMany call with a transparent identifier (an anonymous-type instance holding the 'parent' cnt and the 'child' categoy). The Where filter is applied on the anonymous-type instance, and then we do another Select projection to get back the 'parent'. The Single call was always 'outside' the query expression of course, so it should be obvious how that fits in.

For more information, I suggest reading Jon Skeet's article How query expressions work.

Upvotes: 1

diceguyd30
diceguyd30

Reputation: 2752

Here is a non-direct translation that I believe performs the same task in much less code:

var myContentObj = context.CmsContents.Single(
                        x => x.ContentId == myCurrentContentId && 
                        x.CmsCategories.Any(y => y.CategoryId == myCurrentCategoryId)
                    );

Upvotes: 1

Related Questions