Jean
Jean

Reputation: 5101

How to cache with EFCore in ASP.NET 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 Asp.net core?

  2. EFCore open-source extension, which includes much more than just caching http://entityframework-plus.net/


The solution I am using:

in startup.cs:
services.AddMemoryCache();


in view/controller:
var LAST_SEARCHS_COUNT = 5;
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...

Upvotes: 3

Views: 2228

Answers (1)

El Duderino
El Duderino

Reputation: 1392

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.

Upvotes: 2

Related Questions