Exclude certain entities from second-level caching

caching entity-framework entity-framework-6

Question

In my EF environment, I'm utilizing EFCache to offer second-level caching.

I encountered a challenge since one of my entities is linked to a view that offers row-level security. As a result, this view filters rows depending on a few criteria. All users will receive the same outcome when using the second-level cache!

Any assistance would be appreciated as I'm searching for a solution to prevent some entities from being cached.

My cache setting is as follows:

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));
    }
}
1
1
11/24/2015 5:16:31 AM

Accepted Answer

I discovered the solution in this article.

You must develop a caching policy and drive a class from in order to exclude specific things.CachingPolicy .

Having overriddenCanBeCached technique, you could do so.false to stop caching.

I've got a functioning code here:

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);
        }
    }
}
4
11/24/2015 5:45:10 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow