首页 > 解决方案 > 包括所有具有递归属性的导航属性 EF Core

问题描述

我试图急切地加载与实体相关的所有数据,但我仍然对像这样的递归属性有疑问:

  public class Node : BaseAbstractEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }


    [ForeignKey("TypeId")]
    public virtual NodeType Type { get; set; }
    public int? TypeId { get; set; }


    [ForeignKey("ParentId")]
    public virtual Node Parent { get; set; }
    public int? ParentId { get; set; }


    public ICollection<Node> Children { get; set; }
}

我在这种方法中使用它:

 public async Task<object> JustGetAsync(Type type, JObject value, DbContext context)
    {
        int id = 0;
        if (value != null && value["id"] != null)
            id = Int32.Parse(value["id"].ToString());

        if (id != 0)
            return await context.FindAsync(type, id);

        var TypeSet = (IQueryable<object>) context.GetType()
                                                  .GetMethod("Set")
                                                  .MakeGenericMethod(type)
                                                  .Invoke(context, null);

        return await TypeSet.Include(context.GetIncludePaths(type)).ToListAsync();
    }

get IncludePaths 是我在此处找到的代码 在此处输入链接描述,有助于渴望所有属性:

public static IQueryable Include(this IQueryable source, IEnumerable navigationPropertyPaths) where T : class { return navigationPropertyPaths.Aggregate(source, (query, path) => query.Include(path)); }

    public static IEnumerable<string> GetIncludePaths(this DbContext context, Type clrEntityType)
    {
        var entityType = context.Model.FindEntityType(clrEntityType);
        var includedNavigations = new HashSet<INavigation>();
        var stack = new Stack<IEnumerator<INavigation>>();
        while (true)
        {
            var entityNavigations = new List<INavigation>();
            foreach (var navigation in entityType.GetNavigations())
            {
                if (includedNavigations.Add(navigation))
                    entityNavigations.Add(navigation);
            }
            if (entityNavigations.Count == 0)
            {
                if (stack.Count > 0)
                    yield return string.Join(".", stack.Reverse().Select(e => e.Current.Name));
            }
            else
            {
                foreach (var navigation in entityNavigations)
                {
                    var inverseNavigation = navigation.FindInverse();
                    if (inverseNavigation != null)
                        includedNavigations.Add(inverseNavigation);
                }
                stack.Push(entityNavigations.GetEnumerator());
            }
            while (stack.Count > 0 && !stack.Peek().MoveNext())
                stack.Pop();
            if (stack.Count == 0) break;
            entityType = stack.Peek().Current.GetTargetType();
        }
    }

标签: c#.netasp.net-core.net-coreentity-framework-core

解决方案


推荐阅读