Change Tracking in EF Core

Change Tracking in EF Core:

Change tracking in EF Core automatically tracks the state of entities (e.g., Added, Modified, Deleted, Unchanged) as they are loaded, modified, and saved. When SaveChanges() is called, EF Core compares the current state of an entity to its original state and generates the necessary SQL commands (e.g., INSERT, UPDATE, DELETE).

By default, EF Core tracks changes to entities as they are modified. However, change tracking can introduce overhead, so it is important to optimize performance when appropriate.

Optimization Techniques:

AsNoTracking(): Use for read-only queries to disable change tracking and improve performance.

Manual Detaching: Detach entities when no longer needed to reduce memory usage.
While change tracking simplifies state management and SQL generation, it should be disabled for read-only operations to minimize performance overhead.

Example:
var blog = context.Blogs.First();
blog.Name = "Updated Name";  // EF Core tracks this change
context.SaveChanges();


 

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced