Course contentsShow
← C#
Lesson 1067 of 1,90810. Entity Framework Core ModelingFree lesson

AsNoTracking Optimization

Retrieve read-only data with reduced overhead by disabling change tracking.

In this lesson, you will learn how to boost your application's performance by disabling EF Core’s change tracking when you only need to read data.

The "Overhead" of Change Tracking

By default, when you retrieve entities from the database using Entity Framework Core, the DbContext keeps a snapshot of those objects. This is known as change tracking. It allows EF Core to automatically detect any changes you make to an object’s properties and save them back to the database with a simple SaveChangesAsync() call.

While this is incredibly convenient for updating records, it comes with a memory and performance cost. Each tracked object must be stored in the internal state manager, and EF Core must perform snapshots to compare values. If you are just generating a report, displaying a list, or performing a read-only operation, this overhead is wasted effort.

Implementing AsNoTracking

To bypass this mechanism, you use the .AsNoTracking() extension method on your IQueryable queries. This tells EF Core to fetch the data from the database, map it to your entities, and then immediately "forget" about them.

// Expensive: EF Core tracks these objects for potential updates
var allUsers = await _context.Users.ToListAsync();

// Efficient: EF Core fetches the data without tracking changes
var readOnlyUsers = await _context.Users
    .AsNoTracking()
    .ToListAsync();

By adding .AsNoTracking(), your application uses less memory and executes faster because the DbContext doesn't have to maintain a reference to those objects or perform identity resolution.

When to use it

Think of AsNoTracking as your default choice for read-only scenarios. If you are retrieving data that will never be modified during the scope of that DbContext instance, there is no reason to pay the "tax" of change tracking.

Note that if you decide you actually do need to save changes later, you cannot simply save an entity retrieved via AsNoTracking without manually re-attaching it, but in the context of pure read operations, this optimization is a simple and effective way to refine your data access layer.

Key Takeaway: Use .AsNoTracking() to improve performance and reduce memory consumption whenever you are performing read-only queries that do not require EF Core's change tracking features.