【问题标题】:How to get list of latest entry for each parent using entity framework?如何使用实体框架获取每个父母的最新条目列表?
【发布时间】:2022-11-26 09:00:28
【问题描述】:

我有一个名为“Children”的表,其中包含“Id”、“ParentId”、“Description”、“LastUpdate”等列。我想查询一个列表,每个 parentId 都有不同的行,我希望这些行是最新的到“LastUpdate”列的值,即 DateTime。 实现这一目标的最简单方法是什么? 我试过这样的事情:

var latestList = _context.Children.where(x => !x.Deleted).OrderByDescending(x => x.LastUpdate).DistinctBy(x => x.ParentId).ToList();

但是这个不能翻译成sql。那我现在还能做什么?

【问题讨论】:

  • 你放错了标签。你用哪个EF?
  • 你能告诉我们ChildrenParent 表的详细信息吗?此外,我们是否也可以包括您的预期输出?

标签: c# entity-framework entity-framework-core entity-framework-6


【解决方案1】:

如果我正确理解您的查询,对于每个 Parent,您都需要具有最新 LastUpdateChild

var latestList = _context.Children
    .Where(x => !x.Deleted)
    .GroupBy(x => x.ParentId)
    .Select(g => g.MaxBy(x => x.LastUpdate))
    .ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多