I need to transform some paginated data from Linq to Entity Framework.
The data should be displayed in MVC Contrib Grid / Pager, so it needs to be paginated and the backend SQL Server should paginate the data.
So I have this code as a working base:
MyEntities db = new MyEntities();
IQueryable<HighScore> highscores = db.HighScores.OrderBy(s => s.Id);
return View(highscores.AsPagination(page.GetValueOrDefault(1), 10));
This generates a pretty paged SQL query with SELECT TOP (10) ... WHERE rownum ETC..
Great, backend SQL Server pagination, the way it should be.
So now I need to transform my entities to a little bit different model.
private HighScoreModel GetUrlForImage(string userId, int? score, bool isAnonymous)
{
return new HighScoreModel
{
// transformation, left out for simplicity
};
}
I can’t simply do:
var fixedData = from v in highscores
select GetUrlForImage(v.UserId, v.Score, v.IsAnonymous);
because that will get me (expected):
LINQ to Entities does not recognize the method 'MvcContribTest.Models.HighScoreModel GetUrlForImage(System.String, System.Nullable1[System.Int32], Boolean)’ method, and this method cannot be translated into a store expression.`
So I need ToList() the entities in order to call my translation method, something like this:
var fixedData = from v in highscores.ToList()
select GetUrlForImage(v.UserId,v.Score,v.IsAnonymous);
Which technically now works, but I have lost the backend SQL Server pagination because the ToList() conversion from IQueryable().
How can I do a server side pagination in this scenario?
What about applying pagination before the ToList then do the transformation:
EDIT: To use with the MVC Contrib grid you will need to wrap it up with the
CustomPagination<T>class this is built in in MVC Contrib: