How does Entity Framework work with recursive hierarchies? Include() seems not to work with it

前端 未结 15 1719
再見小時候
再見小時候 2020-11-28 21:53

I have an Item. Item has a Category.

Category has ID, Name, Parent

15条回答
  •  醉梦人生
    2020-11-28 22:15

    Use this extension method which calls the hard-coded version of Include, to achieve a dynamic depth level of inclusion, it works great.

    namespace System.Data.Entity
    {
      using Linq;
      using Linq.Expressions;
      using Text;
    
      public static class QueryableExtensions
      {
        public static IQueryable Include(this IQueryable source,
          int levelIndex, Expression> expression)
        {
          if (levelIndex < 0)
            throw new ArgumentOutOfRangeException(nameof(levelIndex));
          var member = (MemberExpression)expression.Body;
          var property = member.Member.Name;
          var sb = new StringBuilder();
          for (int i = 0; i < levelIndex; i++)
          {
            if (i > 0)
              sb.Append(Type.Delimiter);
            sb.Append(property);
          }
          return source.Include(sb.ToString());
        }
      }
    }
    

    Usage:

    var affiliate = await DbContext.Affiliates
      .Include(3, a => a.Referrer)
      .SingleOrDefaultAsync(a => a.Id == affiliateId);
    

    Anyway, meanwhile, join the discussion about it on the EF repo.

提交回复
热议问题