我正试图将这个简单的SQL转换为LINQ查询语法。任何帮助将不胜感激。
SELECT p.PID, Count(distinct c.templateID) as AssocTempCnt
FROM Parent p
LEFT JOIN Child c on p.PID = c.PID
GROUP BY p.PID
说明:我有一个父表,其子项可能在子表中有关联。我想知道父PID与之关联的唯一TemplatesID数量(如果有的话)。
PID,描述
1,ABC
2,XYZ
TemplateID,PID,REASON
23,1,ANY
23,1,AGAIN
24,1,不同的
PID - 1 AssocTempCnt - 2
PID - 2 AssocTempCnt - 0
答案 0 :(得分:3)
以下是技巧
from p in Parent
join c in Child on p.PID equals c.PID
into cGrp
select new {
p.PID,
AssocTempCnt = cGrp.Select(x => x.templateID).Distinct().Count()
};
据LinqPad说, 它被翻译成:
SELECT [t0].[PID], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t1].[templateID]
FROM [Child] AS [t1]
WHERE [t0].[PID] = [t1].[PID]
) AS [t2]
) AS [AssocCount]
FROM [Parent] AS [t0]
应该足够好了!
答案 1 :(得分:0)
我怀疑以下LINQ是否会完全转换回原始SQL,但从逻辑上讲它将是:
from p in Parent
join c in Child on p.PID equals c.PID into pcg
from pc in pcg.DefaultIfEmpty()
select new {
p.PID,
count = (pcg == null ? (int?)null :
(int?)pcg.GroupBy(x => x.templateID).Count())
}
或者两者之间是否已有导航属性:
db.Parents
.Select(p => p.Children == null ? null :
p.Children.GroupBy(c => c.templateID).Count()
);