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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With