如何将 SQL Inner Join、Group By 转换为 Linq?
Posted
技术标签:
【中文标题】如何将 SQL Inner Join、Group By 转换为 Linq?【英文标题】:How To Translate SQL Inner Join, Groupby Into Linq? 【发布时间】:2021-10-08 11:50:15 【问题描述】:这里我有 SQL 查询,现在我正在尝试将其转换为 linq,但不知道如何去做,并且卡在从 ChapterQuestion
表中获取 ChapterId
。
任何有关翻译的帮助都将不胜感激。
谢谢
下面是我的sql查询
SELECT CQ.ChapterId,CQS.SetNumber,count(distinct CQ.ChapterQuestionId) as questioncount FROM
[dbo].[ChapterQuestion] AS CQ
JOIN [dbo].[ChapterQuestionSet] AS CQS ON CQ.ChapterQuestionSetId = CQS.ChapterQuestionSetId
WHERE CQ.ChapterId = 1 group by CQS.SetNumber,CQ.ChapterId
下面是我的linq
var list = (from CQS in uow.Repository<ChapterQuestionSet>().GetAll().ToList()
join CQ in uow.Repository<ChapterQuestion>().FindBy(x => x.ChapterId == chapterId).ToList()
on CQS.ChapterQuestionSetId equals CQ.ChapterQuestionSetId
group CQ by CQS into G1
select new ChapterQuestionSetVM
ChapterQuestionSetId = G1.Key.ChapterQuestionSetId,
Count = G1.Count(t => t.ChapterQuestionSetId != null),
QuestionSetNo = $"Question set G1.Key.SetNumber",
ChapterId = // how do i get chapterid from ChapterQuestion
).ToList();
【问题讨论】:
这都是黑盒代码。它不知道它是如何转换成 SQL 的。 【参考方案1】:这是更正的查询。我希望Repository.GetAll()
返回IQueryable
?
此查询仅适用于 EF Core 5.x
var query =
from CQS in uow.Repository<ChapterQuestionSet>().GetAll()
join CQ in uow.Repository<ChapterQuestion>().GetAll() on CQS.ChapterQuestionSetId equals CQ.ChapterQuestionSetId
where CQ.ChapterId == 1
group CQ by new CQS.SetNumber, CQ.ChapterId into G1
select new ChapterQuestionSetVM
ChapterId = G1.Key.ChapterId
QuestionSetNo = $"Question set G1.Key.SetNumber",
Count = G1.Select(t => t.ChapterQuestionSetId).Distinct().Count(),
;
var list = query.ToList();
【讨论】:
将 Linq2DB 解决方案并排放置是一个好地方:P以上是关于如何将 SQL Inner Join、Group By 转换为 Linq?的主要内容,如果未能解决你的问题,请参考以下文章
MySQL Multiple INNER JOIN + GROUP BY 未按预期工作
EF INNER JOIN,LEFT JOIN,GROUP JOIN