I use AsNoTracking()
and know that the first-level caching is disabled when using it. But how can using AsNoTracking()
improve the performance? Wha
AsNoTracking()
means that the entities will not be cached locally by the ObjectContext instance. This has a few practical benefits:
Memory Usage: Since the ObjectContext isn't referencing the entities after they're returned to you, the Garbage Collector can get rid of them as soon as you're no longer referencing them. Normally, the ObjectContext would need to be disposed before this could happen.
Performance: Since EF doesn't have to try to match every record returned from the database with a local entity in the identity map, your queries might execute slightly faster.
Currency: Since queries return entities materialized directly from the database results and do not rely on a local cache, the returned entities should always reflect the latest values in the database.
Statelessness: Since the entities are not being tracked by ObjectContext, you can continue to use the same ObjectContext instance indefinitely for read-only queries and need not feel constrained by the normal advice regarding having short-lived ObjectContexts.
AsNoTracking()
is a good idea if you're only querying entities. It won't work if you need to update them, that is the tradeoff.