简体   繁体   English

EF Core - 如何包含子实体但限制返回的子实体数量

[英]EF Core - How to Include child but limit the number of child entities returned

I am using .NET Core 3.1.我正在使用 .NET Core 3.1。 I have a parent with thousands of child elements, but I only want to retrieve the latest 10 children (and later will use pagination).我有一个有数千个子元素的父级,但我只想检索最新的 10 个子级(稍后将使用分页)。 When I run the following query:当我运行以下查询时:

context.Parent.Include(p => p.Child)

it will return all children and is incredibly slow.它会返回所有孩子,而且速度非常慢。 How can I return only 10 children and later use it for pagination?如何仅返回 10 个孩子,然后将其用于分页? EF prevents using lambdas inside the Include, for example context.Parent.Include(p => p.Child.Take(10)) throws an exception. EF 阻止在 Include 中使用 lambda,例如context.Parent.Include(p => p.Child.Take(10))会引发异常。

Do I need multiple calls to the DB?我需要多次调用数据库吗?

I hope this query helps.我希望这个查询有帮助。

var result = Parentlist
.Select(a => new { a, Childs = a.Childs.Take(10).ToList() })
.AsEnumerable() 
.Select(x =>
{
    x.a.Childs = x.Childs;
    return x.a;
}).ToList();
    var model = context.parent.Where(condition).OrderBy(x).Take(y).Skip(z)
    .select(c=> new parentViewModel 
    {
        Id = c.Id,
        Name= c.Name,
        children = c.children.where(condition)
                    .OrderByDescending(x=> x.CreateDate)
                    .take(pageSize)
                    .Select(x => new childViewModel {
                      Id = x.Id,
                      ChildName = x.Name
                       });
    }); 

What if you write the query starting from the children如果您从孩子开始编写查询怎么办

Context.Chidlren.Where(x => condition ( x.Parent)).Include(x => x.Parent).Take(10).Select(x=> x.Parent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM