当使用Entity Framework时,我很好奇include应该在调用链中的哪个位置被调用。
考虑下面的方法:
// sample usage from service layer
// _customerRepository.Paginate(1, out totalRecords, 25, "DateJoined DESC, AmountSpent", "DateJoined >= '2009-02-01'", "Invoices, Refunds");
public virtual IQueryable<T> Paginate(int page, out int total, int pageSize, string sort = "Id", string filter = null, string includes = null)
{
IQueryable<T> query = DatabaseSet;
total = query.Count(); // get total # of records (required for pagination)...
var skipTo = GetValidSkipCount(page, total, pageSize);
if (!String.IsNullOrWhiteSpace(filter))
{
query.Where(filter);
}
// should includes be before filtering?
// should query.Count() be called after query.Include?
// does it matter?
if (!String.IsNullOrWhiteSpace(includes))
{
query.IncludeMany(includes); // my own extension that takes comma separated string of entities to include
}
return query.OrderBy(sort).Skip(skipTo).Take(pageSize);
}
我的问题是:
- 在调用链中,Include应该始终放在第一位吗?
- Count()是否受到Include的影响?如果是,我猜应该在Include之后进行Count
- 在筛选(Where)之前还是之后应该包括Include?
- 真的很重要吗,因为EF足够“聪明”可以自己解决一切?