How to make Entity Framework cache some objects

33,505

Solution 1

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.

Solution 2

You could take a look at Jaroslaw Kowalski's excellent tracing and caching provider wrappers for Entity Framework.

Share:
33,505
Eugeniu Torica
Author by

Eugeniu Torica

Updated on August 06, 2022

Comments

  • Eugeniu Torica
    Eugeniu Torica over 1 year

    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.