简体   繁体   English

如何使用实体框架获取每个父母的最新条目列表?

[英]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.

相关问题 实体框架 - 获取最新条目的数据库映射 - Entity Framework - Database mapping to get latest entry 如何使用实体框架和MySQL(包括相关实体)获取每个组的最新记录 - How to get latest record for each group using Entity Framework and MySQL including related entity 如何使用Entity Framework获取表中的最新行(考虑性能)? - How to get the latest row in a table using Entity Framework (considering performance)? 使用实体框架选择子对象列表时如何获得对相关父对象的引用 - How do get reference to a related parent object when selecting a list of child objects using entity framework 如何使用 Entity Framework Core 从子表列表的每个订单中获取产品行? - How to get product row from each order of child table list using Entity Framework Core? 获取实体框架中按不同属性分组的最新项目列表 - Get a list of the latest items grouped by a different property in Entity Framework 如何获取父实体框架的子项 - How to get childs of child of a parent Entity Framework 在实体框架的每个父属性中获得最佳结果 - Get top result in each parent property in Entity Framework 如何使用身份列表从实体框架获取ObjectResult - How to get ObjectResult from Entity Framework using a list of Identities 使用实体框架在列表中获取行索引 - Get Row Index in a list by using entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM