Sobes.tech
Middle

What is change tracking?

sobes.tech AI

Answer from AI

Change tracking is a mechanism in ORM (Object-Relational Mapper), such as Entity Framework, that monitors the state of entities (objects) loaded into the data context. It determines which entities have been added, modified, or deleted so that when changes are saved to the database, the appropriate INSERT, UPDATE, or DELETE commands are executed.

Entity states:

  • Added: The object has just been created and added to the context but has not yet been saved to the database.
  • Unchanged: The object has been loaded from the database or has been saved, and no changes have been made.
  • Modified: One or more properties of the object have been changed after loading from the database or saving.
  • Deleted: The object is marked for deletion from the database.
  • Detached: The object is not being tracked by the data context.
// Example of change tracking in Entity Framework Core
using (var context = new MyDbContext())
{
    // Load entity
    var myEntity = context.MyEntities.Find(1);

    // Check initial state
    Console.WriteLine($"Initial state: {context.Entry(myEntity).State}"); // Will output Unchanged

    // Change a property
    myEntity.MyProperty = "New Value";

    // Check state after modification
    Console.WriteLine($"State after modification: {context.Entry(myEntity).State}"); // Will output Modified

    // Add a new entity
    var newEntity = new MyEntity { MyProperty = "Another New One" };
    context.MyEntities.Add(newEntity);

    // Check state of the added entity
    Console.WriteLine($"State of new entity: {context.Entry(newEntity).State}"); // Will output Added

    // Mark an entity for deletion
    context.MyEntities.Remove(myEntity);

    // Check state after removal
    Console.WriteLine($"State after removal: {context.Entry(myEntity).State}"); // Will output Deleted

    // Save changes to the database
    context.SaveChanges();
}
What is change tracking? — C# - sobes.tech