【问题标题】:Finally got Include working with child objects in Entity Framework 6.1终于在 Entity Framework 6.1 中包含使用子对象
【发布时间】:2018-04-23 17:29:18
【问题描述】:

我使用的是通用存储库模式,所以让它发挥作用至关重要。我在网上的几个地方读到,一旦查询的形状发生变化,Entity Framework 将开始忽略 Includes。解决方法是将包含移动到查询的末尾。这对我不起作用。事实上,正好相反。我将 Where 语句移到了 Includes 查询的末尾。

这就是我所拥有的。

public Task<List<T>> ItemsWithAsync(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includeProperties)
        {
            IQueryable<T> query = null;
            if (predicate != null)
                query = _context.Set<T>().Where(predicate);
            else
                query = _context.Set<T>();

            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }

            return query.ToListAsync();
        }

这就是现在适合我的方法。

public Task<List<T>> ItemsWithAsync2(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includeProperties)
        {                
            var query = _context.Set<T>() as IQueryable<T>; // _dbSet = dbContext.Set<TEntity>()

            query = includeProperties.Aggregate(query, (current, property) => current.Include(property)).Where(predicate);

            return query.AsNoTracking().ToListAsync(); 
        }

对我来说关键是将 .Where(predicate) 移动到处理所有包含属性的查询的末尾。

在我的例子中,这会为每条记录返回所有父对象和两个子对象。在此修复之前,我会获取所有的 Parent 对象,并且只有 4 条记录会包含 Child 对象。

这是我调用方法的方式。

using (var uow = _unitOfWorkFactory.Create())
            {

                return (await uow.OfferRepository.ItemsWithAsync2(o =>
                        o.Deleted == false
                        && o.StartDate <= clientDateTime
                        && o.ExpiryDate >= clientDateTime, o => o.Merchant, o => o.App)).ToList();
            } 

希望这会有所帮助!我搜索了几天和几天。我从来没有找到发布的确切解决方案,这就是我发布它的原因。如果这是解决问题的有效方法,任何人都可以发表评论吗?另外,实际需要 query.AsNoTracking 吗?谢谢!

【问题讨论】:

    标签: entity-framework entity-framework-6 repository-pattern unit-of-work


    【解决方案1】:

    这就是现在适合我的方法。

    public Task<List<T>> ItemsWithAsync2(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includeProperties)
            {                
                var query = _context.Set<T>() as IQueryable<T>; // _dbSet = dbContext.Set<TEntity>()
    
                query = includeProperties.Aggregate(query, (current, property) => current.Include(property)).Where(predicate);
    
                return query.AsNoTracking().ToListAsync(); 
            }
    

    对我来说关键是将 .Where(predicate) 移动到处理所有包含属性的查询的末尾。

    在我的例子中,这会为每条记录返回所有父对象和两个子对象。在此修复之前,我会获取所有的 Parent 对象,并且只有 4 条记录会包含 Child 对象。

    这也适用于嵌套的子对象,例如 o.Merchant.Locations。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 2017-07-13
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      相关资源
      最近更新 更多