C# 如何查询缓存而不是实体?
情景:C# 如何查询缓存而不是实体?,c#,asp.net,design-patterns,entity-framework-4,appfabric,C#,Asp.net,Design Patterns,Entity Framework 4,Appfabric,情景: CustomerEntity表示数据库中的Customer表 有几个查询返回CustomerTities(列表和单个客户) 如何“伪造”(代理?)CustomerEntity,以便所有查询都尝试命中缓存的CustomerEntity。显然,在每个查询中,我可以对每个查询使用cache-aside模式,但我希望对整个Customer表使用它,而不管查询是什么 (缓存在一旁) private static readonly DataCache cache=CacheUtil.Instance
private static readonly DataCache cache=CacheUtil.Instance.cache;
公共列表GetCustomers()
{
字符串cacheKey=“test”;
var list=(list)cache.Get(cacheKey);
if(list==null)
{
使用(var context=DataObjectFactory.CreateContext())
{
var customers=context.Customer.Where(w=>w.CustomerId>10.ToList();
列表=新列表();
foreach(客户中的var客户)
列表。添加(客户);
cache.Put(cacheKey,list);
退货清单;
}
}
其他的
{
退货清单;
}
}
这将需要编写ioobjectset
的自定义实现,该实现将从缓存返回数据或查询真正的内部对象集。此实现的实例将显示在您的上下文中,而不是默认的ObjectSet
。另一种更简单的方法是隐藏上下文并仅通过指定的方法(如GetQuery()
)公开查询-您的所有查询都将使用此方法而不是上下文。客户
,因为上下文
对他们来说是不可访问的
您也可以查看。谢谢您的提示。我得在几天内消化你的答案。您提供的链接是我以前看过的,问题是它不再包含appfabric的包装:(
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;
}
}