locked
Paging in Entity Framework RRS feed

  • Question

  • Hello,

    In Entity Framework, using LINQ to Entities, database paging is usually done in following manner:

    int totalRecords = EntityContext.Context.UserSet.Count;
    var list 	 = EntityContext.Context.UserSet
    			  .Skip(startingRecordNumber)
    			  .Take(pageSize)
    			  .ToList();


    This results in TWO database calls.


    Please tell, how to reduce it to ONE database call.

     

    Thank You.

    • Edited by ASP.NET Thursday, June 25, 2009 11:14 PM
    Thursday, June 25, 2009 11:07 PM

Answers

  • One approach could be, using Esql and mapping a stored procedure to an entity.
    SP will return totalRows as output parameter and current page as resultset.

        CREATE PROCEDURE getPagedList(
        @PageNumber int,
        @PageSize int,
        @totalRecordCount int OUTPUT
        AS
        
        //Return paged records


    Please advise.

    Thank You.

    Wednesday, July 1, 2009 10:44 PM

All replies

  • One approach could be, using Esql and mapping a stored procedure to an entity.
    SP will return totalRows as output parameter and current page as resultset.

        CREATE PROCEDURE getPagedList(
        @PageNumber int,
        @PageSize int,
        @totalRecordCount int OUTPUT
        AS
        
        //Return paged records


    Please advise.

    Thank You.

    Wednesday, July 1, 2009 10:44 PM
  • Hello,

    For a stored procedure that you describe, the way to return the actual rows would be to finish the stored procedure with a SELECT statement that provides all the necessary columns. That said, I need some help in understanding the need to reduce the number of database roundtrips from 2 to 1 for a case like this. Could you please explain it to me?

    Thanks,
    Diego
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, July 6, 2009 7:06 AM
  • I have found that calling skip and take in this manner did not work for a SQL2000 database, only from SQL2005 and SQL2008 onwards.  I think it's because with SQL2000 you can't easily perform a select that returns x number of rows from a certain row onwards.
    Sunday, July 12, 2009 8:21 PM
  • Thanks for replies. I was trying to optimize a page by minimize database calls.
    I was able to do so by calling Function Import method (with ObjectParameter), generated on the objectcontex, to call above stored procedure (which returns resultset & output parameter).
     
    Wednesday, August 12, 2009 3:30 PM
  • Could someone please explain this as code?
    Thursday, November 12, 2009 6:19 PM