我有2张桌子,论坛和帖子 我想要使用新的额外字段检索所有论坛字段:计算属于此论坛的所有帖子。
我现在有这个:
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()
答案 0 :(得分:19)
我想你想要这样的东西:
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会是什么样子......
答案 1 :(得分:4)
如果在linqtosql设计器中将论坛连接到帖子,则会创建一个可以查询的关系属性。
var query =
from f in db.Forums
select new
{
forum = f,
PostCount = f.Posts.Count(p => p.ShowIt == 1)
};