Question

I don't know how to work with nested selects in LINQ. How could I convert this SQl expression to LINQ?

Select i.ID, i.Impression, 
(Select COUNT(ImpressionsId) 
    from DiaryImpressions 
    where DiaryPostsId = '2' AND ImpressionsId = i.ID) as Num from Impressions i
Was it helpful?

Solution

from ...
select new { 
    i.Id, 
    i.Impression, 
    Count = context.DiaryImpressions.Count(d => d.DiaryPostsId == 2 && d.ImpressionsId == i.Id)
 }

If you map your objects properly, you can use child relations directly:

Count = i.DiaryImpressions.Count(d => d.DiaryPostsId == 2)

OTHER TIPS

Seriously? DiaryPostsId is a string? Oh well...

from i in context.Impressions
select new {
    i.ID,
    i.Impressions,
    Num = (from d in context.DiaryImpressions
           where d.DiaryPostsId == "2"
           && d.ImpressionsId == i.ID
           select d).Count()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top