【问题标题】:Linq query is not returning the expected result. 3 tables joinLinq 查询未返回预期结果。 3张表连接
【发布时间】:2020-06-03 09:41:42
【问题描述】:

我尝试使用 Linq 查询计算属于申请人的记录,但它没有返回 expatced 结果。发生乘法。 实际申请者有:

  • 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();

【问题讨论】:

  • 请显示示例数据,您期望它返回什么以及实际返回什么。

标签: c# linq join


【解决方案1】:

实际上,这几乎是意料之中的。您已经平面映射了您的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(), 
        };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多