
June 23, 2025 09:10 by
Peter
We shall study Entity Framework Change Tracking in this article. Now, let's get going.
Comprehending Change Tracking
EF Core uses a technology called change tracking to monitor modifications made to your entities. This aids EF Core in figuring out which SQL commands must be run in order to maintain database changes.
Example
using (var context = new AppDbContext())
{
var employee = context.Employees.FirstOrDefault(e => e.EmployeeId == 101);
employee.City = "Mumbai";
// EF Core tracks the change in the City property.
}
Managing the State of Entities
EF Core tracks the state of each entity (Added, Unchanged, Modified, Deleted) to determine the operations to be performed during SaveChanges.
using (var context = new AppDbContext())
{
var employee = context.Employees.FirstOrDefault(e => e.EmployeeId == 101);
context.Entry(employee).State = EntityState.Modified;
context.SaveChanges();
// The state is set to Modified, prompting and UPDATE command
}
Using No-Tracking Queries
No-tracking queries improve performance for read-only operations by not tracking the entities in the context. This reduces memory usage and speeds up query execution.
using (var context = new AppDbContext())
{
var employees = context.Employees.AsNoTracking().ToList();
// No change tracking is performed, ideal for read-only operations
}
Benefits of No-Tracking Queries
- Performance: Faster queries and lower memory footprint.
- Scalability: Better for large-scale read operations.
- Simplicity: Reduces overhead when changes to entities are not needed
using (var context = new AppDbContext())
{
var employees = context.Employees.AsNoTracking().FirstOrDefault(e => e.EmployeeId == 101);
// Efficiently retrieves the post without tracking it's state
}
Summary
- Change Tracking: Tracks changes to determine necessary database operations.
- Entity State Management: Manages entity states for accurate database updates.
- No-Tracking Queries: Optimizes performance for read-only operations.
In this article, I have tried to cover how to handle Entity Framework Change Tracking.
European Best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.
