Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn off EF change tracking for any instance of the context [duplicate]

I have a context to a read-only database for reporting and I am writing lots of code, like this:

using (var context = new ReportingContext()) {     var reportXQuery = context.ReportX.AsNoTracking();      // Do stuff here with query... } 

Is there a way to set the AsNoTracking bit so that just newing up the ReportingContext above would automatically use AsNoTracking instead of needing to remember to explicitly call it every query?

like image 391
Karl Anderson Avatar asked Sep 20 '13 20:09

Karl Anderson


People also ask

How do I turn off change tracking in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

What is as no tracking in EF?

The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking. We can also change the default behavior of tracking at context instance level.

What difference does AsNoTracking () make?

AsNoTracking() . This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.


1 Answers

Try changing your context constructor to this:

public ReportingContext() { this.Configuration.AutoDetectChangesEnabled = false; } 

EDIT:

This will after all not help you, as stated on Arthur's blog, it is usable only in particular scenarios:

http://blog.oneunicorn.com/2012/03/12/secrets-of-detectchanges-part-3-switching-off-automatic-detectchanges/

like image 120
Admir Tuzović Avatar answered Sep 21 '22 17:09

Admir Tuzović