Feri
Feri

Reputation: 501

Caching entity itself in IMemoryCache in ASP.NET Core MVC with Entity Framework

In an ASP.NET Core MVC app I'm using IMemoryCache in ConfigureServices():

services.AddMemoryCache();

In a controller, I originally had this code:

// List<> of POCOs:
var myLines = await _context.MyEntity.Where(somecondition).ToListAsync();

and I've changed it to:

// List<> of POCOs:
var myLines = await
    _cache.GetOrCreateAsync("mykey",async entry => {
        return
            await _context.MyEntity.Where(somecondition).ToListAsync();
    });

This works well.

But I'm wondering if it is a bad practice anyway or not.

Is it a problem caching attached POCOs?

Upvotes: 0

Views: 451

Answers (1)

Elendil Zheng-MSFT
Elendil Zheng-MSFT

Reputation: 541

This i very basic usage of memory cache, it can meet some basic requirement, but please consider below senario

  1. Your POCO is changed by someone else, how would your cache know that? You'll need some sync task to sync your cache and database data
  2. Your application is going to be delpoyed to a web farm, memery cache only works for just one machine, a request routed to another machine won't have the cache. In this senario you'll need a out of process cache such as redis or even build your own distributed cache.

So it really depends on what is your requirement, if it is simple enough, than this approach is a good practice. Otherwise you need to take the above 2 senario into consideration since these 2 are the most common issue for a cache solution.

Upvotes: 1

Related Questions