我有以下工作正常的 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)
}