How to cache with EFCore in ASP.NET Core entity-framework-core


I have a select query on a table which gives the last searches on the website.

This is for inspiration, and does not require to be updated for every page call, therefore I would like to cache these searches as it begins to show some performances impact.

My website uses ASP.NET Core and EFCore.

I believe there is no built-in way to do that on a single line. What would be the best approach?

I am thinking about updating every 10 minutes the 300 last searches in memory and pick few of them randomly.

Up to now I have found these two options which I could use:

  1. Raw cache method for ASP.Net Core How to cache resources in core?

  2. EFCore open-source extension, which includes much more than just caching

The solution I am using:

in startup.cs:

in view/controller:
var lastSearchs = await Cache.GetOrCreateAsync<List<Search>>("LAST_SEARCHS"
    ,(k)=> {
        k.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
        return (from s in DbContext.Searchs
                orderby s.CreationTime descending
                select s).Take(LAST_SEARCHS_COUNT * 40).ToListAsync();

The impact is quite significant, with calls count divided by more than 100:

Impact of changes...

5/23/2017 12:32:33 PM

Popular Answer

You can use Response Caching

[ResponseCache(VaryByHeader = "User-Agent", Duration = 30)]
public IActionResult About2()

Also Response Caching Middleware

You could also keep a static instance of the DataContext and make sure change tracking is enabled. That will keep it in memory to track changes. It might get slow though.

4/17/2017 8:15:43 PM

Related Questions


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