Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global setting for AsNoTracking()?

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?

like image 963
Vindberg Avatar asked Oct 04 '12 12:10

Vindberg


People also ask

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.

How do you use AsNoTracking in EF core?

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.

What is the use of AsNoTracking in Entity Framework?

AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.


2 Answers

Since this question is not tagged with a specific EF version, I wanted to mention that in EF Core the behavior can be configured at the context level.

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(); } 
like image 84
Amr Elgarhy Avatar answered Oct 08 '22 01:10

Amr Elgarhy


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 
like image 39
Ladislav Mrnka Avatar answered Oct 08 '22 01:10

Ladislav Mrnka