Entity Framework Core Interview Question #190

How can ChangeTracker.Clear help in batch processing?

Testing, Production Practices & Senior Real-World Scenarios Senior Advanced

Quick Interview Answer

ChangeTracker.Clear stops tracking all currently tracked entities efficiently. It can be useful after a completed batch when a context is intentionally reused and those entities are no longer needed. Often, creating a fresh short-lived DbContext per batch is even clearer. Do not clear tracking while pending changes still need to be saved.

Detailed Explanation

ChangeTracker.Clear stops tracking all currently tracked entities efficiently. It can be useful after a completed batch when a context is intentionally reused and those entities are no longer needed. Often, creating a fresh short-lived DbContext per batch is even clearer. Do not clear tracking while pending changes still need to be saved.

Code Example

await db.SaveChangesAsync(cancellationToken);
db.ChangeTracker.Clear();