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();
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.
The AsNoTracking method tells Entity Framework to stop that additional work and so, it can improve the performance of your application.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With