简体   繁体   中英

PredicateBuilder and n+1 query

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM