Select entities with multiple and nested levels without using Include

前端 未结 3 1493
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 06:05

I have the following entity:

public class Item 
{
    public int Id { get; set; }

    public int? ParentId { get; set; }
    public Item Parent { get; set; }         


        
3条回答
  •  被撕碎了的回忆
    2020-12-11 06:39

    Generally speaking, you can't load a recursive structure of unknown unlimited depth in a single SQL query, unless you bulk-load all potentially relevant data irregardless whether they belong to the requested structure.

    So if you just want to limit the loaded columns (exclude PropertyB) but its ok to load all rows, the result could look something like the following:

    var parentGroups = dbContext.Items.ToLookup(x => x.ParentId, x => new Projection
    {
        Id = x.Id,
        PropertyA = x.PropertyA
    });
    
    // fix up children
    foreach (var item in parentGroups.SelectMany(x => x))
    {
        item.Children = parentGroups[item.Id].ToList();
    }
    

    If you want to limit the number of loaded rows, you have to accept multiple db queries in order to load child entries. Loading a single child collection could look like this for example

    entry.Children = dbContext.Items
        .Where(x => x.ParentId == entry.Id)
        .Select(... /* projection*/)
        .ToList()
    

提交回复
热议问题