Help with IQueryables and lazyLoading in asp.net mvc
Say i want to add pagination support. My app is separated in Web, Services and repositories.
The Controller only speaks to the Service and the Service g开发者_运维百科ets Data and does business logic.
Say i want pagination support.. I have this method in my ContributorService
public IQueryable<Contributor> GetContributors(int page, int pageSize)
{
return _repository.GetAll().OrderBy(c=>c.ACC_CREATEDATE).Skip((page)*pageSize).Take(pageSize);//solo temporalmente
}
is that ok?? or should the OrderBy, Skip, Take be done in the repository?
which currently only does this
public IQueryable<Contributor> GetAll()
{
return db.Contributors;
}
I would add the query to the business object ( I think you dont have one, do you), there you may have a base version of it, and another one for the paged data. And would expect to service to execute that query by calling the ToList, I find it dangerous to return a query object to the controller.
Your repository might have a GetPartial Method, with the sort, from, to, and a filter params. If you have a generic service, you might also implement this in that generic service.
public List<Contributor> GetPartial<TSortBy>(Expression<Func<Contributor, TSortBy>> sortByExpr, Expression<Func<Contributor, bool>> filterExpr, int pageNo, int pageSize)
{
var query = db.Contributors;
if (filterExpr != null)
query.Where(filterExpr);
query.orderBy(sortByExpr).Skip (...).Take(...).ToList();
}
if you have a Repository class, you can add this method. By the way, I am using Dynamic LINQ, which makes it easier to pass order by expression as plain text (just like sql)
精彩评论