see on GitHub

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 HasChanges property and WhatChanged method are available in Advanced session operations.

HasChanges

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

Syntax

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 session. Including name of the field/property that changed, its old and new value and change type.

Syntax

IDictionary<string, DocumentsChanges[]> WhatChanged();

ReturnValue
IDictionary<string, DocumentsChanges[]> Dictionary containing list of changes per document key.

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"];
	DocumentsChanges.ChangeType change = employeeChanges[0].Change; // DocumentsChanges.ChangeType.DocumentAdded
}

Example II

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

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