在不使用 Skip() 或 Take() 的情况下缓存分页 LINQ 结果

问题描述 投票:0回答:2

我正在使用 LINQ 在我的网站中分页数据。我目前正在使用 Skip() 和 Take() 来执行分页。现在我想使用缓存依赖项来缓存数据,这样如果数据发生变化,缓存就会失效。但是 SQL Server 的查询通知不支持 TOP 表达式。是否有其他方法可以使用不生成 TOP 的 LINQ 查询分页数据集?或者另一种方式来缓存这些数据,使其失效?

sql-server linq pagination sqlcachedependency
2个回答
1
投票

分两遍提取数据:

// 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();

1
投票

缓存整个结果集,并将 SqlDependancy 设置为该结果集。

从缓存中读取整个集合,然后使用“跳过/接受”。

© www.soinside.com 2019 - 2024. All rights reserved.