Tracking vs No Tracking Queries in EF Core

Tracking Queries

By default, EF Core tracks changes to entities fetched from the database. This allows modifications and later saving of changes (e.g., INSERT, UPDATE, DELETE when SaveChanges() is called). Tracking is useful when entities need to be updated or deleted.

Use Case:

When entities need to be modified or saved.

Example:

var blog = context.Blogs.First();

blog.Name = "Updated Name";  // EF Core tracks the change

context.SaveChanges();

 

No Tracking Queries

When only reading data (without modification), use .AsNoTracking() to disable change tracking. This improves performance and reduces memory usage, especially with large datasets.

Use Case:

For read-only operations to improve performance, particularly with large datasets.

Example:

var blogs = context.Blogs.AsNoTracking().ToList();  // No tracking of entities

 

Summary:

Tracking: Entities are tracked, and changes can be saved.

No Tracking: No entity state tracking, which enhances performance for read-only queries.

 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced