Skip to main content
How to Clear a Session

How to Clear a Session

  • Use the Clear() method to clear the session’s state:
    it removes ALL tracked entities and cancels ALL pending operations (e.g., Store, Delete).
    This is useful when you need to discard all tracked changes and reset the session state.

  • To remove only a single entity from tracking, see Evict a single entity.

  • In this article:


Clear the session's state

using (var session = store.OpenSession())
{
// Store a new employee
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Doe"
};
session.Store(newEmployee, "employees/1");

// Load an existing employee and modify it
var existingEmployee = session.Load<Employee>("employees/2");
existingEmployee.LastName = "UpdatedLastName";

// Load another employee and mark for deletion
var employeeToDelete = session.Load<Employee>("employees/3");
session.Delete(employeeToDelete);

// At this point:
// * employees/1 is pending insert
// * employees/2 is pending update
// * employees/3 is pending delete

// Clear the session state
// this will remove all tracking and pending operations
session.Advanced.Clear();

// SaveChanges does nothing - all operations were discarded
session.SaveChanges();
}

Syntax

void Clear();