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?
Using
.Single, .First, .Whereetc 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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With