2014-11-01 62 views
0

我有3個表, 1是存儲所有用戶數據的用戶表,另一個是應用表,最後是用戶教育表, 這些表之間的關係:Linq查詢和由表中的數據分組具有一對多關係?

an user can have many applications, and also can have many education background

問題 這裏就是我要選擇從申請表的月度報告數據,我想小組由各個教育水平我的數據,根據每個用戶的最高學歷,就像這樣:

user A - high school 
user A - bachelor degree 
user A - master degree 
user B - high school 
user C - bachelor degree 
user D - high school 

會結果:

master degree : total 1 
bachelor degree : total 1 
high school : total 2 

我已經試過這樣:

var edu = CTX.user_applications.Where(a => a.applied_date >= new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1) 
                 && a.applied_date <= DateTime.Now 
                ).GroupBy(g => (g.user_list.user_edus.OrderByDescending(o => o.edu_lvl_id).FirstOrDefault())) 
                  .Select(x => new ReportObject 
                  { 
                   Key = x.Key.ToString(), 
                   Count = x.Count().ToString() 
                  }).ToList(); 

錯誤:

A group by expression can only contain non-constant scalars that are comparable by the server. The expression with type 'System.Data.Linq.EntitySet`1[OTOKarir.Models.user_edu]' is not comparable 

這是行不通的,它給我一個錯誤,還有必須的一些竅門做是正確的,順便說一句,我不是很確定它會給我想要的結果,我與這個stug,需要一些指導,任何想法會非常偉大?謝謝。

application table and education table both have foreign key from table user list

+0

它給你什麼錯誤? – 2014-11-01 12:04:48

+0

@KundanSinghChouhan我編輯了我的帖子與發生錯誤。 – NomNomNom 2014-11-01 12:47:43

+0

你也可以提供你的數據庫結構嗎? – 2014-11-01 13:22:33

回答

1

您正在訂購的物品是:user_edu。這應該是一個標量。這可以通過選擇其edu_lvl_id輕鬆完成。

只顯示必要的部分,這是你應該做的:

var edu = CTX.user_applications 
      .GroupBy(g => (g.user_list 
          .user_edus.OrderByDescending(o => o.edu_lvl_id) 
          .FirstOrDefault() 
          .edu_lvl_id)); // This is added 

邊注:在分組LINQ到SQL是非常低效的,因爲對於每個組單獨查詢被執行填充組中的項目。您可以考慮首先在內存中執行分組(LINQ到對象)。然後你可以再次將對象分組。

+0

啊現在工作!你指出我正確的方向,thx隊友! – NomNomNom 2014-11-02 07:46:08