Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding AsNoTracking in Entity Framework impact a Count?

Does adding AsNotracking function to a count in Entity Framework 6 has an impact on a count? More specifically does it improve or decrease performance or will the count result get cached?

With AsNoTracking

myContext.Products.AsNoTracking().Count();

Without AsNoTracking

myContext.Products.Count();
like image 241
Valderann Avatar asked Apr 11 '19 10:04

Valderann


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.

Does AsNoTracking increase performance?

The AsNoTracking method tells Entity Framework to stop that additional work and so, it can improve the performance of your application.

How do I turn off change tracking in Entity Framework?

In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities.

What does EF's DbContext need to be tracking in order to delete a row from the database?

The approach that you adopt to deleting entities via the DbContext depends on whether the context is currently tracking the entity being deleted or not. In the following example, the entity to be deleted is obtained by the context, so the context begins tracking it immediately.


1 Answers

Since no entities are being generated with this query, there is nothing to track, therefore no difference in performance. The SQL generated from this would look something like this:

SELECT COUNT(1)
FROM [dbo].[Products]

which obviously returns a single row. If it was creating entities to be tracked, it would have to return every single entity in that table.

like image 183
DavidG Avatar answered Oct 20 '22 20:10

DavidG