Linq 查询未返回预期结果. 3 个表连接



>我尝试使用 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();

这实际上是意料之中的。你已经平面映射了你的applicantsapplicationcourse基本上在你的连接子句中乘以 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(), 
};

最新更新