Global setting for AsNoTracking()?

Vindberg picture Vindberg · Oct 4, 2012 · Viewed 27k times · Source

Originally I believed that

context.Configuration.AutoDetectChangesEnabled = false;

would disable change tracking. But no. Currently I need to use AsNoTracking() on all my LINQ queries (for my read only layer). Is there a global setting to disable tracking on the DbContext?

Answer

Ladislav Mrnka picture Ladislav Mrnka · Oct 4, 2012

What about simply exposing method like this on your derived context and use it for queries:

public IQueryable<T> GetQuery<T>() where T : class {
    return this.Set<T>().AsNoTracking();
}

Setting AsNoTracking globally is not possible. You must set it per each query or per each ObjectSet (not DbSet). The latter approach requires using ObjectContext API.

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var set = objectContext.CreateObjectSet<T>();
set.MergeOption = MergeOption.NoTracking;
// And use set for queries