簡體   English   中英

EF Core - 如何包含子實體但限制返回的子實體數量

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

我正在使用 .NET Core 3.1。 我有一個有數千個子元素的父級,但我只想檢索最新的 10 個子級(稍后將使用分頁)。 當我運行以下查詢時:

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

它會返回所有孩子,而且速度非常慢。 如何僅返回 10 個孩子,然后將其用於分頁? EF 阻止在 Include 中使用 lambda,例如context.Parent.Include(p => p.Child.Take(10))會引發異常。

我需要多次調用數據庫嗎?

我希望這個查詢有幫助。

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
                       });
    }); 

如果您從孩子開始編寫查詢怎么辦

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