Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter where AsNoTracking in Entity Framework is called

Does it matter where the AsNoTracking method is called when writing an Entity Framework query? e.g.

var matchingCustomers = context.Customers.AsNoTracking().Where(n => n.city == "Milan").Skip(50).Take(100).OrderBy(n => n.Name).ToList(); var matchingCustomers = context.Customers.Where(n => n.city == "Milan").AsNoTracking().Skip(50).Take(100).OrderBy(n => n.Name).ToList(); var matchingCustomers = context.Customers.Where(n => n.city == "Milan").Skip(50).AsNoTracking().Take(100).OrderBy(n => n.Name).ToList(); var matchingCustomers = context.Customers.Where(n => n.city == "Milan").Skip(50).Take(100).AsNoTracking().OrderBy(n => n.Name).ToList(); var matchingCustomers = context.Customers.Where(n => n.city == "Milan").Skip(50).Take(100).OrderBy(n => n.Name).AsNoTracking().ToList(); var matchingCustomers = context.Customers.Where(n => n.city == "Milan").Skip(50).Take(100).OrderBy(n => n.Name).ToList().AsNoTracking(); 

I like adding it to the end of statements but before the ToList is called like this:

var matchingCustomers = context.Customers.Where(n => n.city == "Milan").Skip(50).Take(100).OrderBy(n => n.Name).AsNoTracking().ToList(); 
like image 548
user1786107 Avatar asked Feb 22 '16 12:02

user1786107


People also ask

What does AsNoTracking do in Entity Framework?

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.

How do you use as no tracker?

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.

When an object is returned with a NoTracking merge option load can only be called?

InvalidOperationException: When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects. Try disabling proxy creation.


1 Answers

No it doesn't matter: (source)

A new query with NoTracking applied, or the source query if NoTracking is not supported.

So you either do it in the beginning and you expand the "new" query with the method chain, or you do it in the end and then get the "new" query. As long as you call it before the query is executed you're fine.

like image 145
Alexander Derck Avatar answered Oct 08 '22 15:10

Alexander Derck