在LINQ表达式中嵌套选择,如何?

时间:2011-12-02 20:22:27

标签: sql linq sql-to-linq-conversion

我不知道如何使用LINQ中的嵌套选择。 我怎么能把这个SQl表达式转换成LINQ?

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

2 个答案:

答案 0 :(得分:2)

真的? DiaryPostsId是一个字符串?哦,好吧......

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()
}

答案 1 :(得分:0)

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

如果您正确映射对象,可以直接使用子关系:

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