如何查询缓存而不是实体
本文关键字:实体 缓存 何查询 查询 | 更新日期: 2023-09-27 17:52:58
场景:
- CustomerEntity表示数据库中的Customer表。
- 有几个查询返回CustomerEntities(列表和单个客户)
如何可能"伪造"(代理?)CustomerEntity,以便所有查询尝试命中缓存的CustomerEntities。显然,在每个查询中,我可以对每个单独的查询使用缓存旁边模式,但是我想对整个Customer表使用它,而不管查询是什么。
(Cache-aside) private static readonly DataCache cache = CacheUtil.Instance.Cache;
public List<Customer> GetCustomers()
{
string cacheKey = "test";
var list = (List<Customer>)cache.Get(cacheKey);
if (list == null)
{
using (var context = DataObjectFactory.CreateContext())
{
var customers = context.Customer.Where(w => w.CustomerId > 10).ToList();
list = new List<Customer>();
foreach (var customer in customers)
list.Add(customer);
cache.Put(cacheKey, list);
return list;
}
}
else
{
return list;
}
}
这将需要编写IObjectSet<T>
的自定义实现,它将从缓存返回数据或查询真正的内部ObjectSet<T>
。此实现的实例将在您的上下文中公开,而不是默认的ObjectSet<T>
。另一种更简单的方法是简单地隐藏上下文并仅通过指定的方法(如GetQuery()
)暴露查询-所有查询都将使用此方法而不是context.Customer
,因为它们将无法访问context
。
你也可以选择缓存上下文包装