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
- sync_session
- async_session
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();
}
using (var asyncSession = store.OpenAsyncSession())
{
// Store a new employee
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Doe"
};
await asyncSession.StoreAsync(newEmployee, "employees/1");
// Load an existing employee and modify it
var existingEmployee = await asyncSession.LoadAsync<Employee>("employees/2");
existingEmployee.LastName = "UpdatedLastName";
// Load another employee and mark for deletion
var employeeToDelete = await asyncSession.LoadAsync<Employee>("employees/3");
asyncSession.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
asyncSession.Advanced.Clear();
// SaveChangesAsync does nothing - all operations were discarded
await asyncSession.SaveChangesAsync();
}
Syntax
void Clear();