簡體   English   中英

Linq 查詢未返回預期結果。 3表連接

[英]Linq query is not returning the expected result. 3 tables join

我嘗試使用 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();

這實際上是非常預期的。 您已經平面映射了您的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(), 
        };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM