Search code examples
c#entity-frameworkcachingmemorycache

caching EF Poco objects is bad?


Is it a good practice to cache EF Poco object directly using MemoryCache? What are disadvantages if there are?

for example, I created a Poco class called category

public partial class Category  
{
    public int Id { get; set; } 
    public string Name { get; set; }        
    public string Description { get; set; }
}

then I add list of category into the cache object which is type of MemoryCache as below

protected ObjectCache Cache
{
    get
    {
        return MemoryCache.Default;
    }
}

List<Category> data= getCategories();
Cache.Add(new CacheItem(key, data), policy);

Or is it suggested to use another converter class in between and cache this class rather than Poco class itself?


Solution

  • There's nothing wrong in caching results from an expensive database call. Just make sure that those objects are eagerly initialized so that later when you try to read them from the cache they don't need an open DbContext. EF's delayed loading could bite you if you haven't fully initialized the object that's been stored into the cache.

    Also make sure that you have a good cache eviction policy when the data is updated. With In-memory cache things could get very, very, very tricky if you are running your application in a web-farm.