最后得到包含在Entity Framework 6.1中使用子对象

时间:2018-04-23 17:29:19

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

我使用的是Generic Repository模式,因此我必须让它工作。我在线阅读了几个地方,一旦查询的形状发生变化,实体框架将开始忽略包含。修复是将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(谓词)移动到处理所有includedProperties的查询的末尾。

在我的例子中,这将返回每个记录的所有Parent对象和两个Child对象。在此修复之前,我将获得所有Parents对象,并且只有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实际需要吗?谢谢!

1 个答案:

答案 0 :(得分:0)

现在这对我有用。

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(谓词)移动到处理所有includedProperties的查询的末尾。

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

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