2010-05-04 82 views
8

我有2个表格,论坛和帖子。
我想检索所有论坛字段与一个新的额外字段:计数属于此论坛的所有帖子。Linq加入COUNT

我有这个现在:

var v =(from forum in Forums 
    join post in Posts on forum.ForumID equals post.Forum.ForumID 
    select new 
    { 
     forum, //Need to retrieve all fields/columns from forum  
     PostCount = //count all post that belong to this forum with a condition: count it only if post.Showit==1 

    } 
    ).Distinct() 
  1. 的加入必须LEFT JOIN:如果没有职位属于一些论坛,论坛的字段应被检索但PostCount场应为0。
  2. 结果集必须是不同的(加盟给我的全交叉...或者它怎么叫)
+0

任何人都知道,如果我可以在SQL服务器上做些什么来优化这些查询?我有同样的情况,但需要多个Count()结果 – 2010-05-04 22:44:19

回答

16

我想你想要的东西,如:

from forum in Forums 
// ForumID part removed from both sides: LINQ should do that for you. 
// Added "into postsInForum" to get a group join 
join post in Posts on forum equals post.Forum into postsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = postsInForum.Where(post => post.ShowIt == 1).Count() 
} 

或(在评论中指出),你可以把一个条件在Count电话 - 我总是忘记的可用:)

from forum in Forums 
// ForumID part removed from both sides: LINQ should do that for you. 
// Added "into postsInForum" to get a group join 
join post in Posts on forum equals post.Forum into postsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = postsInForum.Count(post => post.ShowIt == 1) 
} 

“显示”为唯一的过滤另一种选择职位将要做到这一点的加入:

from forum in Forums 
join post in Posts.Where(post => post.ShowIt == 1) 
    on forum equals post.Forum into shownPostsInForum 
select new 
{ 
    Forum = forum, 
    // Select the number of shown posts within the forum  
    PostCount = shownPostsInForum.Count() 
} 

我相信,所有的这些都逻辑正确的,但我不知道SQL将是什么样子?

+0

难道你不能'PostCount = g.Count(post => post.ShowIt == 1)'?或者仅用于LinqToObject? – ANeves 2010-05-04 16:44:57

+0

@sr pt:是的,好点。将编辑:) – 2010-05-04 16:45:26

+0

你能否请求解释单词“进入”它的使用;不应该用于“组”? – shivesh 2010-05-04 16:49:00

2

如果您将论坛连接到linqtosql设计器中的帖子,这将创建可查询的关系属性。

var query = 
    from f in db.Forums 
    select new 
    { 
    forum = f, 
    PostCount = f.Posts.Count(p => p.ShowIt == 1) 
    };