Skip to main content

Session: Deleting Entities

Entities can be marked for deletion by using the Delete method, but will not be removed from the server until SaveChanges is called.

Syntax

void Delete<T>(T entity);

void Delete(string id);

void Delete(string id, string expectedChangeVector);
Parameters
entity or idT or stringinstance of the entity to delete or entity ID
expectedChangeVectorstringa change vector to use for concurrency checks

Example I

Employee employee = session.Load<Employee>("employees/1");

session.Delete(employee);
session.SaveChanges();

If UseOptimisticConcurrency is set to 'true' (default 'false'), the Delete() method will use loaded 'employees/1' change vector for concurrency check and might throw ConcurrencyException.

Example II

session.Delete("employees/1");
session.SaveChanges();

In this overload, the Delete() method will not do any change vector based concurrency checks because the change vector for 'employees/1' is unknown.

If entity is not tracked by session, then executing

session.Delete("employees/1");

is equal to doing

session.Advanced.Defer(new DeleteCommandData("employees/1", changeVector: null));

In this sample the change vector is null - this means that there will be no concurrency checks. A non-null and valid change vector value will trigger a concurrency check.

You can read more about defer operations here.