Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 and caching of query results

Tags:

Say I have a table or 2 that contains data that will never or rarely change, is there any point of trying to cache those data? Or will the EF context cache that data for me when I load them the first time? I was thinking of loading all the data from those tables and use a static list or something to keep that data in memory and query the in memory data instead of the tables whenever I need the data within the same context. Those tables I speak of contains typically a few hundred rows of data.

like image 911
OKB Avatar asked Jun 21 '11 06:06

OKB


People also ask

Does Entity Framework cache query results?

Each time you try to make a query, Entity Framework checks cache containing complied SQL statements to see if there is an already compiled statement it can re-use with parameters. If that statement is not found, Entity Framework has to compile C# query to Sql again.

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.

Does EF core cache data by default?

The Cache: The memory cache is used by default.

What is query result cache?

A result cache is an area of memory, either in the Shared Global Area (SGA) or client application memory, that stores the results of a database query or query block for reuse. The cached rows are shared across SQL statements and sessions unless they become stale.


1 Answers

The EF context will cache "per instance". That is, each instance of the DbContext keeps it's own independent cache of objects. You can store the resulting list of objects in a static list and query it all you like without returning to the database. To be safe, make sure you abandon the DbContext after you execute the query.

var dbContext = new YourDbContext(); StaticData.CachedListOfThings = dbContext.ListOfThings.ToList(); 

You can later use LINQ to query the static list.

var widgets = StaticData.CachedListOfThing.Where(thing => thing.Widget == "Foo"); 

The query executes the in-memory collection, not the database.

like image 195
Ed Chapel Avatar answered Sep 22 '22 15:09

Ed Chapel