1

我有以下工作正常的 SQL

SELECT 
    f.ForumId, 
    f.Name, 
    COUNT(ft.TopicId) AS TotalTopics, 
    COUNT(fm.MessageId) AS TotalMessages
FROM 
    tblForumMessages fm INNER JOIN
    tblForumTopics ft ON fm.TopicId = ft.TopicId RIGHT OUTER JOIN
    tblForums f ON ft.ForumId = f.ForumId
GROUP BY f.ForumId, f.Name

我正在尝试转换为 Linq。

这就是我所拥有的

 var forums =   (from f in Forums
                join ft in ForumTopics on f.ForumId equals ft.ForumId into topics
                from y in topics.DefaultIfEmpty()
                join fm in ForumMessages on y.TopicId equals fm.TopicId into messages
                from x in messages.DefaultIfEmpty()
                select new { f.ForumId, f.Name, y.TopicId, x.MessageId } into x
                group x by new { x.ForumId, x.Name } into g
                select new
                    {
                        ForumId = g.Key.ForumId,
                        ForumName = g.Key.Name,
                        TopicCount = g.Count(i => i.TopicId),
                        MessageCount = g.Count(i => i.MessageId)
                    }
                ).ToList();

TopicCount = g.Count(i => i.TopicId)说无法将表达式类型“System.Guid”转换为返回类型“bool”时出现错误。

我缺少什么来完成这项工作?

谢谢

* 编辑*

多亏了 Rob,我才开始工作,但即使没有记录,主题计数和消息计数的计数总是返回 1。两者都应该返回 0。

我通过更改修改了查询

select new { f.ForumId, f.Name, y.TopicId, x.MessageId } into x

select new
{
    f.ForumId, f.Name, 
    TopicId = y != null ? y.TopicId : (Guid?)null,
    MessageId = z != null ? z.MessageId : (Guid?)null
} into x

对于实际计数,我将查询更改为

select new
{
    g.Key.ForumId,
    g.Key.Name,
    TopicCount = g.Count(t => t.TopicId != null),
    MessageCount = g.Count(t => t.MessageId != null)
} 
4

2 回答 2

2

有问题的文章是TopicCount = g.Count(i => i.TopicId)。该Count方法采用 a Func<T, bool>(它给出集合中满足谓词的项目数)。

看起来您想要TopicId组中不同 s 的数量。尝试替换TopicCount = g.Count(i => i.TopicId)TopicCount = g.GroupBy(i => i.TopicId).Count().

于 2013-11-01T19:55:03.097 回答
0

你也可以试试TopicCount = g.Select(i => i.TopicId).Distinct().Count()

于 2013-11-01T20:15:07.877 回答