>我尝试使用 Linq 查询计算属于申请人的记录,但它没有返回 expated 结果。发生乘法。 实际申请人有:
- 2 应用
- 6 课程
如何联接表以获得正确的值(2 和 6(?
谢谢!
var q = from application in this.SzakokRepository.GetAll()
join course in this.ErettsegiRepository.GetAll() on application.JelentkezoId equals course.JelentkezoId
join applicants in this.JelentkezokRepository.GetAll() on application.JelentkezoId equals applicants.Id
where applicants.Id == jelentkezoID
select new
{
Jelentkezo = applicants, //1 pieces
Szak = application, //2 pieces
Erettsegi = course, //6 pieces
};
var result = from g in q
group g by g.Jelentkezo.Id into grp
select new HelperErettsegiSzak
{
JId = grp.Key,
CountedApplications = grp.Count(), //12 pieces
CountedCourses = grp.Select(x => x.Erettsegi.Id).Count(), //12 pieces
};
return result.ToList();
这实际上是意料之中的。你已经平面映射了你的applicants
,application
和course
基本上在你的连接子句中乘以 1*2*6 = 12,然后按键分组,这对连接结果中的所有项目都是相同的,并且有一组 12 个项目。尝试在计数中添加Distinct
子句(假设Szak
有一些独特的Id
字段(:
var result = from g in q
group g by g.Jelentkezo.Id into grp
select new HelperErettsegiSzak
{
JId = grp.Key,
CountedApplications = grp.Select(x=> x.Szak.Id).Distinct().Count(),
CountedCourses = grp.Select(x => x.Erettsegi.Id).Distinct().Count(),
};