Akb*_*ari 2 caching entity-framework entity-framework-6
我正在使用EFCache在我的 EF 上下文中提供二级缓存。
我遇到了一个问题,我的一个实体连接到一个提供行级安全性的视图。所以这个视图根据一些参数过滤行。使用二级缓存时,所有用户都会得到相同的结果!
我正在寻找一种从缓存中排除某些实体的方法,欢迎提供任何帮助。
这是我的缓存配置:
class CacheConfiguration : DbConfiguration
{
public CacheConfiguration()
{
var transactionHandler = new CacheTransactionHandler(new InMemoryCache());
AddInterceptor(transactionHandler);
var cachingpolicy = new cachingpolicy();
Loaded +=
(sender, e) => e.ReplaceService<DbProviderServices>(
(s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy));
}
}
Run Code Online (Sandbox Code Playgroud)
我在这篇博文中找到了答案。
为了排除某些实体,您需要创建缓存策略并从CachingPolicy.
覆盖CanBeCached方法后,您可以返回false以防止缓存。
这是我的工作代码:
class CacheConfiguration : DbConfiguration
{
public CacheConfiguration()
{
var transactionHandler = new CacheTransactionHandler(new InMemoryCache());
AddInterceptor(transactionHandler);
//var cachingPolicy = new CachingPolicy();
var cachingPolicy = new myCachingPolicy();
Loaded +=
(sender, e) => e.ReplaceService<DbProviderServices>(
(s, _) => new CachingProviderServices(s, transactionHandler, cachingPolicy));
}
}
public class myCachingPolicy : CachingPolicy
{
protected override bool CanBeCached(System.Collections.ObjectModel.ReadOnlyCollection<System.Data.Entity.Core.Metadata.Edm.EntitySetBase> affectedEntitySets, string sql, IEnumerable<KeyValuePair<string, object>> parameters)
{
string[] excludedEntities = {
"permView1",
"permView2",
"permView3"};
if (affectedEntitySets.Where(x => excludedEntities.Contains(x.Table)).Any())
{
return false;
}
else
{
return base.CanBeCached(affectedEntitySets, sql, parameters);
}
}
}
Run Code Online (Sandbox Code Playgroud)