Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Entity Framework cache some objects

I'm using Entity Framework.

In my database are stored persons and country of their origins. When I'm loading a person object I wan't to know what is the place each person originates. Is there a way to cache list of countries so that there wouldn't be unnecessary requests.

like image 681
Eugeniu Torica Avatar asked Jul 18 '09 14:07

Eugeniu Torica


People also ask

Does Entity Framework cache queries?

It is very simple to understand. The first time a query is invoked, data is retrieved from the database and stored in memory before being returned. The compiled queries could be cached for the life of an app pool instance and provided to the Entity Framework for low latency performance of data access.

Does Entity Framework cache data?

Entity Framework has the following forms of caching built-in: Object caching – the ObjectStateManager built into an ObjectContext instance keeps track in memory of the objects that have been retrieved using that instance. This is also known as first-level cache.


1 Answers

As Luhmann has already said my mate Jarek has an excellent sample Caching provider for the Entity Framework. Which he talks about here.

However sometimes this approach is overkill, and I suspect that caching countries is a good example where the effort isn't worth it. It maybe better to implement some sort of ad-hoc caching.

If you try to do this the main problem you will run into is that an instance Entity Framework entity can only be attached to one ObjectContext at a time, which means if you are getting concurrent requests (like in a website) you will have problems is you just grab items from the cache and use them blindly.

What you need is a cloning cache, i.e. so when you grab something from the cache it clones them.

I put together a tip that illustrates how to do this Tip 14 - How to cache Entity Framework Reference Data

Hope this helps

Alex James

Entity Framework Team Microsoft.

like image 67
Alex James Avatar answered Oct 11 '22 14:10

Alex James