C# .NET Core 3.1-Linq-选择按唯一属性分组的记录
在.Net framework中,我有一个工作查询:C# .NET Core 3.1-Linq-选择按唯一属性分组的记录,c#,entity-framework-core,C#,Entity Framework Core,在.Net framework中,我有一个工作查询: IEnumerable<Cars> LatestCars = await _context.Cars.Where(x => x.IsActive == true && x.IsDeleted == false) .GroupBy(y => y.ManufacturerId) .Select(z => z.OrderBy
IEnumerable<Cars> LatestCars = await _context.Cars.Where(x => x.IsActive == true && x.IsDeleted == false)
.GroupBy(y => y.ManufacturerId)
.Select(z =>
z.OrderByDescending(k => k.ReleaseDate)
.FirstOrDefault()
)
.OrderByDescending(l => l.ReleaseDate)
.Take(5)
.ToListAsync();
你有什么建议吗?谢谢。EF Core从版本3开始,在表达式只能在本地执行时引发异常。实际上,问题不在于
.OrderByDescending()
本身,而是查询包含分组,分组只支持将结果聚合为标量的Select()
投影。因为只有这样才能转换为SQL GROUP BY语句
有一种简便的方法可以解决这个问题。如果您有一个Manufacturer
模型,其中包含一个IEnumerable Cars
导航属性,您可以从那里开始,这将导致一个可翻译的查询
因此,在您的情况下,此工作查询可以是以下内容:
Manufacturers.Select(m=>m.Cars.OrderByDescending(c=>c.ReleaseDate.FirstOrDefault())
.OrderByDescending(c=>c.ReleaseDate).Take(5)
缺点是,如果制造商有0辆车,则此列表中可能有null
值,因此通常最好将这些值过滤掉,但在这种情况下,OrderByDescending()
可以大大缓解这一问题
另一种可能的解决方案是查询有限数量的项目,然后继续在本地工作:
Cars.OrderByDescending(c=>c.ReleaseDate).Take(100).ToList()
.GroupBy(c=>c.ManufacturerId).选择(g=>g.First()).Take(5)
这样做的缺点是,结果可能会少于5个。试着看看这个:,它可能会帮助你,我不知道你在选择中选择了什么。@KarelKřesťan谢谢你。现在可以了。
System.InvalidOperationException: The LINQ expression '(GroupByShaperExpression:
KeySelector: (g.ManufacturerId),
ElementSelector:(EntityShaperExpression:
EntityType: Cars
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
)
)
.OrderByDescending(p => p.ReleaseDate)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync().