Linq查询和分组表中的数据具有一对多的关系?

时间:2014-11-01 10:57:06

标签: c# asp.net .net linq linq-to-sql

我有3张桌子,  1是存储所有用户数据的用户表,另一个是应用表,最后是用户教育表, 这些表之间的关系:

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

它不起作用,它给我一个错误,必须有一些技巧才能正确地做到这一点,顺便说一下我不确定它会给我想要的结果,我是这样做的,需要一些指导,任何想法都会很棒? THX。

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

2 个答案:

答案 0 :(得分: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-to-SQL中的分组效率非常低,因为对于每个组,执行单独的查询以填充组中的项目。您可以考虑首先获取数据并在内存中进行分组(LINQ到对象)。然后你可以再次按对象分组。

答案 1 :(得分:0)

看一下这个答案:LINQ GroupBy on multiple ref-type fields; Custom EqualityComparer

它解释了GroupBy只能用于实现IEqualityComparer<T>接口的类型。

为了了解您的查询是否正确,我们需要您执行查询的数据的DB结构/类型。