30

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?

Karl Anderson
  • 33,426
  • 12
  • 62
  • 78

1 Answers1

22

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/

Admir Tuzović
  • 10,517
  • 7
  • 31
  • 69
  • 4
    Could you elaborate a bit on the difference between `AutoDetectChangesEnabled = false` and `AsNoTracking`? – Gert Arnold Sep 20 '13 at 20:28
  • Actually after reading the thread in the comment above, seems that my answer will not help you much. I was sure that this configuration setting affects change tracking globally but it seems it does not affect it in a way you want it. Sorry :) – Admir Tuzović Sep 20 '13 at 20:34
  • Setting `AutoDetectChangesEnabled` to `false`...It just disables the automatic call of `DetectChanges` http://stackoverflow.com/questions/16863382/dbcontext-autodetectchangesenabled-set-to-false-detecting-changes – Jaider Sep 12 '16 at 15:52