1

I use PredicateBuilder to pass a Dynamic Expression to a method in my repository that uses it within Where clause. Here is the relevant repository code:

        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();

In my controller I have this:

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);

When I make a reference to a property of "Owner" it makes another roundtrip to the database, causing an n+1 query problem. Is there any workaround to avoid this?

Gene Belitski
  • 10,270
  • 1
  • 34
  • 54
Jose Gregorio
  • 59
  • 1
  • 8

1 Answers1

3

Do the includes before the AsExpandable like so:

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();
LostInComputer
  • 15,188
  • 4
  • 41
  • 49
  • Thx a lot, the only thing that need change its that the context.Set() returns DbQuery in wich i cannot call .Include, i end up with putting var results = context.Set().Where(where); and then return results.AsExpandable().ToList(); – Jose Gregorio Jan 08 '14 at 16:58