如何手动加载多个子列表,这样它们就不会急切加载或延迟加载?

问题描述 投票:0回答:0

我在 Entity Framework Core 中映射了以下类

public class Parent
{
   public int ParentId { get; set; }
   public virtual List<Child> Children { get; set; }
}

public class Child
{
   public int ParentId { get; set; }
   public int ChildId { get; set; }
   public virtual List<Grandchild> Grandchildren { get; set; }
}

public class Grandchild 
{
   public int ParentId { get; set; }
   public int ChildId { get; set; }
   public int GrandchildId { get; set; }
   public string Something { get; set; }
}

当我从数据库获取

Parent
的实例时,我想立即加载
Children
列表,但我想通过首先在单个查询中加载完整的孙子列表,然后为每个
Grandchildren
元素分配适当的元素来手动加载每个子级的
Child
列表。我之所以要这样做,是因为急切加载孙子元素会产生性能不佳的查询,并且逐一延迟加载每个子元素也表现不佳。

我的问题是我不知道如何让实体框架的更改跟踪器将手动加载的列表视为未更改。

public Parent LoadParent(int id)
{
   // .Include Children but not Grandchildren
   var parent = context.Parents.Where(p => p.ParentId == id)
      .Include(n => n.Children)
      .FirstOrDefault();

   Dictionary<int, List<Grandchild>> grandchildrenDictionary = context.Grandchildren
      .Where(p => p.ParentId == id)
      .GroupBy(k => k.ChildId)
      .ToDictionary(k => k.Key, v => v.ToList())

   foreach (var child in parent.Children)
   {
      // This is where I'm not sure what to do.  How do I assign the Grandchildren
      // elements without making Entity Framework think that child.Grandchildren is
      // changed
      child.Grandchildren = new();
      if (grandchildrenDictionary.TryGetValue(child.ChildId, out List<Grandchild> elements))
      {
         child.Grandchildren.AddRange(elements);
      }
   }

   return parent;
}
c# entity-framework entity-framework-core
© www.soinside.com 2019 - 2024. All rights reserved.