Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Caching with the Repository Pattern

If I want to implement caching when I am using the repository pattern and the Entity Framework, couldn't I just do some simple logic outside of the Entity Framework to handle the caching?

E.g.

if(Cache[ProductsKey] != null)
{
    return ConvertToProducts(Cache[ProductsKey]);
}
else
{
    var products = repository.Products;
    Cache[ProductsKey] =  products;
    return products;
}

It seems like a lot of people are over-complicating this. Or is doing it this way going to be limiting in some way?

like image 633
Joe Avatar asked Apr 11 '11 15:04

Joe


People also ask

Is the repository pattern useful with Entity Framework?

TL;DR – summary. No, the repository/unit-of-work pattern (shortened to Rep/UoW) isn't useful with EF Core. EF Core already implements a Rep/UoW pattern, so layering another Rep/UoW pattern on top of EF Core isn't helpful.

Which caching is supported by the Entity Framework?

Data Points - Second-Level Caching in the Entity Framework and AppFabric.

Does EF core cache data by default?

The Cache: The memory cache is used by default.

What is repository cache?

A cache repository is a storage location where Veeam Backup & Replication keeps temporary cached metadata for the data backed up by the file share backup jobs. For more information about cache repository, see NAS Backup Support. ©2022 Veeam® Software Privacy Notice | Cookie Notice.


1 Answers

I prefer my repository to be clean. I prefer implementing caching in my service layer if needed.

So i 100% agree with your sample. Your repository returns products (by running query) and you can cache it or not in other layers.

P.S.: I assume that you start your object context when it's needed(session start) and dispose it when session ends.

like image 53
Afshin Gh Avatar answered Oct 04 '22 22:10

Afshin Gh