Session: How to Check if There are Any Changes on a Session

Single entity can be checked for changes using HasChanged method, but there is also a possibility to check if there are any changes on a session or even what has changed. Both the HasChanges property and the WhatChanged method are available in the Advanced session operations.

HasChanges

Property indicates if the session contains any changes. If there are any new, changed or deleted entities.

bool HasChanges { get; }

Example

using (IDocumentSession session = store.OpenSession())
{
	Assert.False(session.Advanced.HasChanges);

	session.Store(new Employee
					  {
						  FirstName = "John",
						  LastName = "Doe"
					  });

	Assert.True(session.Advanced.HasChanges);
}

WhatChanged

Method returns all changes for each entity stored within the session. Including name of the field/property that changed, its old and new value, and change type.

IDictionary<string, DocumentsChanges[]> WhatChanged();
ReturnValue
IDictionary<string, DocumentsChanges[]> Dictionary containing list of changes per document ID.

Example I

using (IDocumentSession session = store.OpenSession())
{
	session.Store(new Employee
	{
		FirstName = "Joe",
		LastName = "Doe"
	});

	IDictionary<string, DocumentsChanges[]> changes = session.Advanced.WhatChanged();
	DocumentsChanges[] employeeChanges = changes["employees/1-A"];
	DocumentsChanges.ChangeType change = employeeChanges[0].Change; // DocumentsChanges.ChangeType.DocumentAdded
}

Example II

using (IDocumentSession session = store.OpenSession())
{
	Employee employee = session.Load<Employee>("employees/1-A"); // 'Joe Doe'
	employee.FirstName = "John";
	employee.LastName = "Shmoe";

	IDictionary<string, DocumentsChanges[]> changes = session.Advanced.WhatChanged();
	DocumentsChanges[] employeeChanges = changes["employees/1-A"];
	DocumentsChanges change1 = employeeChanges[0]; // DocumentsChanges.ChangeType.FieldChanged
	DocumentsChanges change2 = employeeChanges[1]; // DocumentsChanges.ChangeType.FieldChanged
}