Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache table with entity framework

I have some data tables that almost never change so I don't want to call database every time that I run a query on db-context. In NHibernate, there is an option to do so on the mapper: Cache.ReadOnly();

And it will read the whole table to your cache on the start up and every time you want to load the object like with lazy loading, it will fetch data from the cached memory instead.

How can I do the same with Entity-Framework?

like image 756
Ashkan S Avatar asked Apr 17 '26 07:04

Ashkan S


1 Answers

Using .Single, .First, .Where etc will not cache the results unless you are using second-level caching.

If you need to cache the result, you need to implement second level caching in EF.

EntityFramework.Cache that enables us caching of query results for EF 6.1 applications.

we need to tell EF to use caching by configuring the caching provider and the transaction handler.

public class Configuration : DbConfiguration
{
    public Configuration()
    {
        var transactionHandler = new CacheTransactionHandler(new InMemoryCache());
        AddInterceptor(transactionHandler);
        var cachingPolicy = new CachingPolicy();
        Loaded +=(sender, args) => args.ReplaceService<DbProviderServices>(
            (s, _) => new CachingProviderServices(s, transactionHandler,
            cachingPolicy));
    }

}
like image 157
Eldho Avatar answered Apr 19 '26 09:04

Eldho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!