Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4 - prevent basic caching

If I have an entity framework 4 context, normally if I have run a query like:

db.Invoices.Where(I => whatever);

and then later run something else:

db.Invoices.Where(I => something_else);

any objects returned from the second query, which were also returned from the first, will not be loaded from the database. EF will just take the object it already has for that key.

Question, what is the best way to turn this feature off? Can I tell EF to load each and every object it needs from the database without exception?

Thanks!

like image 549
Adam Rackis Avatar asked Oct 15 '10 15:10

Adam Rackis


People also ask

Does EF core cache data by default?

The Cache: The memory cache is used by default. The Cache Key: The cache key is created by combining a cache prefix, all cache tags and the query expression. The Query Materialized: The query is materialized by either using "ToList()" method or "Execute()" method for query deferred.

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 Entity Framework cache queries?

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.

What difference does AsNoTracking () make?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.


1 Answers

You need to change the MergeOption setting for your entity, e.g.

db.Invoices.MergeOption = MergeOption.OverwriteChanges;

OverwriteChanges means that objects are always loaded from the data source. You can also use NoTracking to disable tracking completely, which can improve performance if you don't need to make updates to the data or re-use the queries. The default value is AppendOnly which has the behaviour you've observed.

like image 91
Simon Steele Avatar answered Sep 23 '22 21:09

Simon Steele