通用递归“包含”-EF

时间:2019-04-23 16:33:33

标签: .net entity-framework entity-framework-6 .net-4.7.2

我需要对包含数据库(EF 6.2.0)进行包含的递归调用,是否可以通过通用方式进行?

public class Option
{
    public long OptionID { get; set; }

    public long Property1 { get; set; }

    public long Property2 { get; set; }

    public long Property3 { get; set; }

    public long Property4 { get; set; }
}

public class ClassOne
{
    public long OrderID { get; set; }

    public long OptionID { get; set; }

    public long Property1 { get; set; }

    public long Property2 { get; set; }

    public long Property3 { get; set; }

    public long Property4 { get; set; }

    public virtual Option Option { get; set; }

    public virtual ICollection<ClassOne> CollectionOne { get; set; } = new HashSet<ClassOne>();

    public virtual ICollection<ClassTwo> CollectionTwo { get; set; } = new HashSet<ClassTwo>();
}

    public ICollection<TEntity> Find(Expression<Func<TEntity, bool>> currentExpression, IncludeProperties includeProperties)
    {
        using (var currentContext = new TContext())
        {
            return (includeProperties == IncludeProperties.None
                    ? new List<Expression<Func<TEntity, object>>>()
                    : PropertyInfoToExpression(GetVirtualProperties(new TEntity())))
                .Aggregate(currentContext.Set<TEntity>().AsQueryable(),
                    (x, includeProperty) => x.Include(includeProperty)).Where(currentExpression).ToList();
        }
    }

_classOneRepository.Find(x => x.Property1 == 1), IncludeProperties.All);

使用此代码,我可以获得父项的所有集合,但无法获得其子项的集合数据。

1 个答案:

答案 0 :(得分:0)

  

我需要对包含(EF 6.2.0)的数据库进行包含的递归调用

根本不可能。急于使用“ include”进行加载会生成一个大查询来获取所有相关实体,而EF无法使用.NET表达式来表示递归查询,或者无法在SQL中生成一个递归查询。

通过结果进行递归并使用“显式加载”或“延迟加载”来获取子级,或加载所有实体,并让“更改跟踪器”“修复”导航属性。如果您的后端支持递归查询,则可以编写商店查询以获取实体树,以将变更跟踪器编织在一起。