PredicateBuilder和n + 1查询

时间:2014-01-06 16:25:20

标签: c# linq entity-framework asp.net-mvc-4 predicatebuilder

我使用PredicateBuilder将动态表达式传递给我的存储库中的一个方法,该方法在Where子句中使用它。以下是相关的存储库代码:

        var results = context.Set<T>().AsExpandable.Where(where);


        foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            results = results.Include(includeProperty);
        }
        return results.ToList();

在我的控制器中我有这个:

var predicate = PredicateBuilder.True<Account>();
if (amount> 0)
    predicate = predicate.And(d => d.Amount <= amount);


var model = AccountRepository.Get(predicate, "Owner").ToList();
return PartialView(model);

当我对“Owner”的属性进行引用时,它会再次向数据库进行往返,从而导致n + 1查询问题。是否有任何解决方法可以避免这种情况?

1 个答案:

答案 0 :(得分:3)

包括之前 AsExpandable,如下所示:

var results = context.Set<T>()

foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
    results = results.Include(includeProperty);
}

return results.AsExpandable.Where(where).ToList();