sql-serverlinqpaginationsqlcachedependency

Caching paged LINQ results without using Skip() or Take()


I am using LINQ for paging data in my website. I am currently using Skip() and Take() to perform the paging. Now I want to cache the data using cache dependencies so that the the cache will invalidate if the data changes. However SQL Server's query notifications don't support the TOP expression. Are there any alternative ways to query a paged set of data with LINQ that doesn't generate TOP? Or another way to cache this data so that it invalidates?


Solution

  • Pull your data in two passes:

    // step1: get the IDs of the items in the current page.
    List<int> customerIds = db.Customers
      .Where(filter)
      .OrderBy(c => c.FirstName)
      .ThenBy(c => c.CustomerID)
      .Select(c => c.CustomerID)
      .Skip(200)
      .Take(20)
      .ToList();
    
    // step2: get the items for that page
    List<Customer> customers = db.Customers
      .Where(c => customerIds.Contains(c.CustomerID))
      .ToList();