Session: How to Disable Entities Tracking per Session
By default, session is tracking the changes. This means that for each document retrieved, session will start tracking it's changes allowing you to make the modifications and save the entities using the SaveChanges
method.
Sometimes it might be considered an unnecessary overhead (e.g. when session does not plan to make any changes, just retrieve the documents). This is why tracking can be turned off using SessionOptions.NoTracking
property. When turned off, the Store
and SaveChanges
operations will no longer be available (exception will be throw when used) and each call to methods such as Load
will create a new instance of a class that is being returned.
Example
using (IDocumentSession Session = store.OpenSession(new SessionOptions
{
NoTracking = true
}))
{
Employee employee1 = Session.Load<Employee>("employees/1-A");
Employee employee2 = Session.Load<Employee>("employees/1-A");
// because NoTracking is set to 'true'
// each load will create a new Employee instance
Assert.NotEqual(employee1, employee2);
}
using (IAsyncDocumentSession Session = store.OpenAsyncSession(new SessionOptions
{
NoTracking = true
}))
{
Employee employee1 = await Session.LoadAsync<Employee>("employees/1-A");
Employee employee2 = await Session.LoadAsync<Employee>("employees/1-A");
// because NoTracking is set to 'true'
// each load will create a new Employee instance
Assert.NotEqual(employee1, employee2);
}