Ray*_*yes 8 .net sql asp.net-mvc caching entity-framework
我已经组建了一个小型的ASP.NET MVC 2站点,该站点执行一些非常广泛的日期挖掘/表连接/等.
使用MVC,我有一个控制器,以许多不同的形式(表,图像等)返回数据.为了节省频繁访问数据库,我有一个双缓存机制:
OutputCacheAttributewith VaryByParam = "*". System.Runtime.Caching.ObjectCache.ObjectCacheController内部示例:
private static readonly ObjectCache cache =
new MemoryCache("CompareControllerCache");
private static void CacheObject(ViewModel obj,
string param1,
int someOtherParam )
{
string key = string.Format("{0}-{1}", param1, someOtherParam);
Trace.WriteLine(string.Format("Adding {0} to the cache", key));
cache.Add(key, obj, new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromMinutes(1)
});
}
// Corresponding GetCachedObject with similar key defining logic.
Run Code Online (Sandbox Code Playgroud)
这给我带来了良好的性能提升,但失败的地方就是CacheItemPolicy非常简单.理想情况下,我希望缓存窗口更大,但如果数据库发生更改,缓存项目将会过期.
在CacheItemPolicy似乎与支持这个ChangeMonitors集合,而我可以添加SqlChangeMonitor,但要建的时候这是我停下来.
我正在使用Entity Framework 4访问SQL数据库,如何构建SqlChangeMonitor监视可能触发缓存过期的几个数据库表?
SqlChangeMonitor构造有SqlDependency这需要一个SqlCommand-我怎么能锁定在我的数据库的实体框架的封装?
可以在SqlDependency中包装任意LINQ查询,包括EF Linq查询,请参阅LinqToCache.但不幸的是,EF选择为查询制定SQL的方式,即使是最简单的from t in context.table select t,也与Query Notificaiton限制不兼容,并且SqlDependency会立即作为无效语句失效.我在基于SqlDependency的LINQ查询缓存中已经讨论过这个问题.
What you can do is use SqlChangeMonitor with straightforward SqlCommand objects constructed as simple SELECT ... FROM Table on your tables that are likely to change. You need to understand that there is a balance between the cost of setting up notifications and the cost of polling, if your tables change frequently then monitoring for changes could turn out to be more expensive than polling. See this article The Mysterious Notification to understand how QN works and what is the cost of monitoring.
| 归档时间: |
|
| 查看次数: |
5609 次 |
| 最近记录: |