MSDN Documentation

Understanding Entity States in Entity Framework

In Entity Framework (EF), each entity object that is being tracked by the context has an associated entity state. This state indicates whether the entity is new, has been modified, has been deleted, or hasn't changed since it was retrieved from the database.

The entity state is crucial for determining how EF interacts with the database during operations like saving changes. It helps EF generate the correct SQL commands (INSERT, UPDATE, DELETE) to persist the state of your objects to the data source.

Common Entity States

The most common entity states you'll encounter are:

Added

New object, not in database

Unchanged

Object retrieved from database

Modified

Object changed, needs update

Deleted

Object marked for deletion

Detached

Object not tracked

Managing Entity States

The DbContext automatically manages the state of entities that are retrieved from the database or added to the context. You can also manually control the state of entities using the DbSet<TEntity> methods and the Entry() method of the DbContext.

Example: Tracking an entity

When you query an entity, it's initially in the Unchanged state:


using (var context = new MyDbContext())
{
    var product = context.Products.Find(1); // Loads product from database
    // 'product' is now in the Unchanged state
}
        

Example: Marking an entity as Modified

If you modify a property of a tracked entity, EF automatically detects the change and marks the entity as Modified:


using (var context = new MyDbContext())
{
    var product = context.Products.Find(1);
    if (product != null)
    {
        product.Price = 15.99m; // Modify a property
        // EF will automatically mark 'product' as Modified
        context.SaveChanges(); // Generates an UPDATE statement
    }
}
        

Example: Manually setting the state

You can explicitly set the state of an entity using the Entry() method:


var newProduct = new Product { Name = "Gadget", Price = 99.99m };
context.Entry(newProduct).State = EntityState.Added;

var existingProduct = context.Products.Find(2);
context.Entry(existingProduct).State = EntityState.Deleted;
        

EntityState Enum

The System.Data.EntityState enum (or Microsoft.EntityFrameworkCore.EntityState in EF Core) defines the possible states:


public enum EntityState
{
    Detached,
    Unchanged,
    Added,
    Deleted,
    Modified,
    // Other states might exist depending on EF version
}
        

Why Entity States Matter

Understanding and effectively managing entity states is key to leveraging the power of Entity Framework for data persistence and management in your .NET applications.