Reputation: 1937
we are using EF 6.1 and code first along with the Unit of work and repository pattern.
the confusion we are facing is that at many places its written that if we use Skip
& Take
on a Dbset, the paging is automatically handled.
but when we see the query being created, it does not contain any clause for paging.
kindly assist what is the possible case , the sample code is as follows:
public virtual IEnumerable<TEntity> GetSorted(Func<TEntity, Object> order,int skip, int take, params Expression<Func<TEntity, object>>[] includes)
{
IQueryable<TEntity> query = dbSet;
foreach (var include in includes)
{
query = dbSet.Include(include);
}
IEnumerable<TEntity> data = dbSet.OrderBy(order).Skip(skip).Take(take).ToList();
//IEnumerable<TEntity> data = query.OrderBy(order).Skip(skip).Take(take).ToList();
return data;
}
any help appreciated..
Upvotes: 1
Views: 56
Reputation: 49095
Your order
parameter needs to be of Expression<Func<TEntity, TSortBy>>
type in order to match the signature of Queryable.OrderBy()
. When you're passing a delegate (Func<TEntity, Object>
), the only OrderBy()
overload that will match this argument is Enumerable.OrderBy()
and not the Queryable.OrderBy()
that you're expecting (both are extension-methods of course).
When the sorting is being done by Enumerable.OrderBy()
(Linq-to-Objects), the query must be executed first (since Linq-to-Objects is meant for working with objects that are already in memory).
However, when Queryable.OrderBy()
is invoked, the order-by expression is being passed to the Linq provider that is then capable of parsing and translating it to a store query (SQL in this case).
So, when you're passing Func<TEntity, Object>
to OrderBy
, you're getting IEnumerable<TEntity>
in return, and further (chained) calls to Skip()
and Take()
are no longer intercepted by Linq-To-Entities.
This is how your method signature should look like:
public virtual IEnumerable<TEntity> GetSorted<TSortedBy>(Expression<Func<TEntity, TSortedBy>> order, int skip, int take, params Expression<Func<TEntity, object>>[] includes)
See MSDN
Upvotes: 2