Search code examples
asp.net-mvcwebformsentity-framework-4

Entity Framework Paging


I have been looking for code that if I can paging the big data in EF, For example from 1 to 100... or more, the web application is really slow. I have code here but I couldn't found a solution yet.

I'am really need to make the data in page or make the data view faster the records the are more then (1,5000,000) records. Please guys if someone have any code or solution for EF paging or the data can be faster reply to me.

Thank you guys,

[Codes]

var openComplaintsAssignedToOffice = individual.Office.AssignedComplaints
                                                      .ToArray()
                                                      .Where(n => n.Individuals.Any(e => e.Employed))
                                                      .ToArray() ; 

if (!complaintModel.ShowClosedComplaints)
{
    openComplaintsAssignedToOffice = openComplaintsAssignedToOffice.Where(c => c.CurrentStatus != ComplaintStatus.Closed)
                                                                   .ToArray();
}

complaintModel.OpenComplaintsAssignedToMyOffice = openComplaintsAssignedToOffice.OrderByDescending(c => c.UpdatedDateTime)
                                                                                .ToArray();
complaintModel.OpenComplaintsAssignedToMyOffice = openComplaintsAssignedToOffice.OrderByDescending(c => c.UpdatedDateTime)
                                                                                .ToArray();
return complaintModel;

Solution

  • You don't indicate specifically where you're looking to page your data, so for simplicity I'm going to assume it's here:

    individual.Office.AssignedComplaints
    

    (Though, as a side note, you seem to be pretty cavalier about throwing in a .ToArray() here and there. Understand that this could drastically impact performance by forcing the system to load many records into memory before performing a filter on those records which could have better been performed on the data source itself.)

    You can use the .Skip() and .Take() functions to effectively page the results. For example, let's say you have these values:

    var pageSize = 10;
    var currentPage = 3;  // 0-indexed, of course
    

    Given those, you would expect to see records 30-39, correct? So you'd use those values to page the data:

    individual.Office.AssignedComplaints.Skip(pageSize * currentPage).Take(pageSize)
    

    This would result in skipping the first 30 records (0-29) and taking the next 10 records, ignoring the rest. Effectively returning "page 3" of the total result set.

    This paging can be applied anywhere in your overall expression tree where a result set can be filtered. Before or after sorting, before or after a .Where() clause, etc. It's really up to you where it would logically belong based on how you're intending to shape and present the data.