3

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?

1
  • Which version of entity framework are u using ? Commented Jul 18, 2016 at 12:17

2 Answers 2

1

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));
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try Entity Framework Extended Library for your purpose. By means of this library you can write something like this

  //query is cached using the default settings
  var c = db.Countries.Where(t => t.IsActive).FromCache();

It's not exactly what you want but if you using a Repository pattern you can encapsulate this logic.

Another approach: If you want to use only build-in stuff than you can use the Local property.

Example:

db.Countries.Load(); // load to cache
var countriesFromEFCache = db.Countries.Local;

foreach (var county in countriesFromEFCache ) // There is not any db query here
{
  ...
}

3 Comments

Hi Awesome :) Thanks for the response. But it is something else. It will cache the results of the query and you have to write ".FromCache()" on each query that you use. Isn't there any built-in stuff for this simple task?
Unfortunately EF has only first level cache and if it you want more universal approach than you can look at efcache.codeplex.com
@AshkanSirous check my update please, may be it will helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.