Reputation: 5101
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:
Raw cache method for ASP.Net Core How to cache resources in Asp.net core?
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:
Upvotes: 3
Views: 2228
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