我的linq如下:
from ucd in UserCategoryDetails
join uc in UserCategories on ucd.UserCategoryDetailsID equals
uc.UserCategoryDetailsID into ucj from uc in ucj.DefaultIfEmpty()
join uct in UserCategoryTypes on ucd.UserCategoryTypeID equals
uct.UserCategoryTypeID
join cc in UserCategoryColours on ucd.UserCategoryColourID equals
cc.UserCategoryColourID
where
ucd.UserCategoryTypeID == 2 &&
ucd.UserID == 1
group ucd by new {
ucd.UserCategoryDetailsID,
ucd.CategoryName,
cc.UserCategoryColourID,
cc.ImageSrcLarge,
cc.ImageSrcSmall
} into g
select new {
UserCategoryDetailsID = g.Key.UserCategoryDetailsID,
CategoryName = g.Key.CategoryName,
CategoryColourID = g.Key.UserCategoryColourID,
ImageSrcLarge = g.Key.ImageSrcLarge,
ImageSrcSmall = g.Key.ImageSrcSmall,
CategoryCount = g.Count()
}
问题是Count()
生成的sql是COUNT(*)
,这会导致结果搞乱,因为当UserCategories中没有行时它返回1。
有人可以告诉我如何生成LINQ等效的COUNT(uc.ProjectID)
吗?基本上是以下SQL语句但在linq中:
SELECT
[t0].[UserCategoryDetailsID], [t0].[CategoryName],
[t3].[UserCategoryColourID], [t3].[ImageSrcLarge],
[t3].[ImageSrcSmall], COUNT([t1].ProjectID) AS [CategoryCount]
FROM
[UserCategoryDetails] AS [t0]
LEFT OUTER JOIN [UserCategory] AS [t1] ON
[t0].[UserCategoryDetailsID]) = [t1].[UserCategoryDetailsID]
INNER JOIN [UserCategoryType] AS [t2] ON
[t0].[UserCategoryTypeID] = [t2].[UserCategoryTypeID]
INNER JOIN [UserCategoryColour] AS [t3] ON
[t0].[UserCategoryColourID] = [t3].[UserCategoryColourID]
WHERE
([t0].[UserCategoryTypeID] = 2) AND ([t0].[UserID] = 1)
GROUP BY
[t0].[UserCategoryDetailsID], [t0].[CategoryName],
[t3].[UserCategoryColourID], [t3].[ImageSrcLarge],
[t3].[ImageSrcSmall]
答案 0 :(得分:0)
当然,我可能会弄错,但在我看来,您的LINQ查询COUNT(*)
正在对分组进行操作,而不是UserCategory
。
如果将g.Count()
替换为uc.Count()
会怎样?
COUNT(*)
将不会返回1。只有当表格中有1行或更多行且COUNT(ProjectId)
列在其中一行或多行中为COUNT(*)
时,ProjectId
才会低于NULL
。
答案 1 :(得分:0)
我明白了。看起来因为它正在执行COUNT(*)
,所以当项目标识为空时它将返回null
,如Jay所述。然后,这将被视为计数中的1,从而搞砸了结果。
将select的计数部分更改为以下内容非常有效:
CategoryCount = g.Where(grp => grp != null).Count()
感谢您的回复