Global setting for AsNoTracking()?

change-tracking entity-framework

Question

At first, I thought that

context.Configuration.AutoDetectChangesEnabled = false;

would stop change monitoring. But no. I now need usingAsNoTracking() on every LINQ query I make (for my read only layer). Is it possible to turn off tracking on the DbContext globally?

1
53
5/13/2013 4:03:07 PM

Accepted Answer

I wanted to add that the behavior in Core EF might be different from at the context level specified as this question is not associated with a certain EF version.

You can also change the default tracking behavior at the context instance level:

using (var context = new BloggingContext())
{
    context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

    var blogs = context.Blogs.ToList();
}
21
8/9/2017 9:34:04 AM

Popular Answer

What about using a method like this that is just exposed on your derived context for queries:

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

Setting AsNoTracking not feasible on a global scale. You must adjust it for every query or for everyObjectSet (not DbSet The second strategy requires employingObjectContext API.

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow