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 id T or string instance of the entity to delete or entity ID
expectedChangeVector string a change vector to use for concurrency checks

Example I

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

session.Delete(employee);
session.SaveChanges();
Employee employee = await session.LoadAsync<Employee>("employees/1");

session.Delete(employee);
await session.SaveChangesAsync();

Concurrency on Delete

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();
session.Delete("employees/1");
await session.SaveChangesAsync();

Concurrency on Delete

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

Information

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));

Change Vector in DeleteCommandData

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.