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。
答案 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结构/类型。