[英]How to get list of latest entry for each parent using entity framework?
I have a table named "Children" which has columns like "Id", "ParentId", "Description", "LastUpdate" etc. I want to query a list which will have distinct rows for each parentId and I want those rows latest according to the value of the "LastUpdate" column which is a DateTime
.我有一个名为“Children”的表,其中包含“Id”、“ParentId”、“Description”、“LastUpdate”等列。我想查询一个列表,每个 parentId 都有不同的行,我希望这些行是最新的为
DateTime
的“LastUpdate”列的值。 What is the simplest way to achieve this?实现这一目标的最简单方法是什么? I have tried something like this:
我试过这样的事情:
var latestList = _context.Children.where(x => !x.Deleted).OrderByDescending(x => x.LastUpdate).DistinctBy(x => x.ParentId).ToList();
But this couldn't be translated into sql. So what else can I do now?但是这不能翻译成sql。那么我现在还能做什么呢?
If I understand your query correctly, for each Parent
you want the Child
that has the latest LastUpdate
:如果我正确理解您的查询,对于每个
Parent
您都希望Child
具有最新的LastUpdate
:
var latestList = _context.Children
.Where(x => !x.Deleted)
.GroupBy(x => x.ParentId)
.Select(g => g.MaxBy(x => x.LastUpdate))
.ToList();
You can order the children before .ToList();
您可以在
.ToList();
之前订购孩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.