我是Field
实体,我正在寻找一种方法来加载所有嵌套字段树,而无需多个DB查询。我听说过关于这个问题Most efficient method of self referencing tree using Entity Framework的封闭表的解决方案
但我不确定它是最简单的方法(实际上我不知道如何填充闭包表并在查询后映射结果)
而不是我想通过CommonId加载所有字段,但我不会通过导航属性从缓存加载数据。
public class Field
{
public int Id { get; s; };
public CommonId{ get; set;} //each field from FieldDetails has same value
[ForeignKey("ParentField")]
public int? ParentFieldId { get; set; }
public virtual Field ParentField {get;set;}
public virtual ICollection<Field> FieldDetails { get; set; } =
new List<Field>();
}
var allFields = Context.Fields.where(f=>f.CommonId == 1).ToList(); //load all fields in memory cache
Field root = Context.Fields.Find(1);
foreach (var f in root.FieldDetails)
{
foreach (var f2 in f.FieldDetails) // should be loaded from cache instead of DataBase Query
{
...
}
}