【问题标题】:Entity Framework get full tree of objects from database实体框架从数据库中获取完整的对象树
【发布时间】:2020-10-24 05:29:19
【问题描述】:

类的结构是这样的:

public class GroupModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; } 
    public int ParentGroupId { get; set; }  
    public List<GroupModel> Groups { get; set; } = new List<GroupModel>();
    [ForeignKey("ParentGroupId")]
    public GroupModel ParentGroup { get; set; } 
    public List<BuildingModel> Buildings { get; set; } = new List<BuildingModel>();
}

public class BuildingModel
{
    public int Id { get; set; }
    public int GroupId { get; set; }
    public string Title { get; set; }   
    public List<FlatModel> Flats { get; set; } = new List<FlatModel>(); 
    [ForeignKey("GroupId")]
    public GroupModel Group { get; set; }
}

public class FlatModel
{
    public int Id { get; set; }
    public int BuildingId { get; set; }
    public string Title { get; set; }
     
    [ForeignKey("BuildingId")]
    public BuildingModel Building { get; set; }
}

一个组可以包括建筑物和其他组。根组引用自身(Id = 0,ParentGroupId = 0)。 问题是如何使用实体框架获得组、建筑物和公寓的完整列表。

如果我使用此代码:

var list = db.groups.Where(x => x.Id == 0)
  .Include(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups) 
  .ToList();

因此,我得到了一棵完整的树(最高到 6 级,但我不再需要它),但它不会分别包括建筑物和公寓。

问题是我如何构建一个完整的组树,以便它还包括建筑物(包括公寓)。

我尝试了不同的组合,但都不起作用:

var list = db.groups.Where(x => x.Id == 0)
  .Include(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups) 
  .Include(x => x.Buildings)
  .ThenInclude(x=>x.Flats) 
  .ToList();

var list = db.groups.Where(x => x.Id == 0)
  .Include(x => x.Groups)
  .Include(x => x.Buildings)
  .ThenInclude(x=>x.Flats) 
  .ThenInclude(x => x.Groups)
  .ThenInclude(x => x.Groups) 
  .ToList();

var list = db.groups.Where(x => x.Id == 0)
  .Include(x => x.Groups)
  .Include(x => x.Buildings)
  .ThenInclude(x=>x.Flats) 
  .Include(x => x.Groups)
  .Include(x => x.Buildings)
  .ThenInclude(x=>x.Flats) 
  .Include(x => x.Groups)
  .Include(x => x.Buildings)
  .ThenInclude(x=>x.Flats) 
  .ToList();
  

我相信这可以通过仅通过第一个代码片段构建组树,然后从数据库中加载所有建筑物并将它们分组来完成,但这不会很快而且不是很正确。

【问题讨论】:

  • 你的意思是像“实体框架加载递归子实体”?我怀疑这在 EF 中可能不是一件容易且高效的事情。

标签: c# asp.net .net entity-framework ef-code-first


【解决方案1】:

我建议你在这种情况下使用LazyLoading,这样你就不需要处理多个Include

延迟加载是一个实体或集合 实体第一次从数据库中自动加载 访问引用实体的属性。

你可以改LazyLoadingEnabled:

this.Configuration.LazyLoadingEnabled = false//true;

欲了解更多信息,请查看Loading Related Entities

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多