Unique Constraints: How to work with unique constraints bundle?

In order to use this bundle first activate it on the server. The description can be found in server section.

To use the Unique Constraint features on the client side you need to reference Raven.Client.UniqueConstraints assembly.

using Raven.Client.UniqueConstraints;

When creating the DocumentStore, you'll need to register the UniqueConstraintsStoreListener in the store, as follows:

store.RegisterListener(new UniqueConstraintsStoreListener());

To define a unique constraint on a property use the UniqueConstraint attribute as shown below:

private class User
{
	[UniqueConstraint]
	public string Name { get; set; }

	[UniqueConstraint]
	public string Email { get; set; }

	public string FirstName { get; set; }

	public string LastName { get; set; }
}

Extension methods

The bundle provides two extension methods for IDocumentSession.

LoadByUniqueConstraint

Allows loading a document by its UniqueConstraint, returning null if the document doesn't exists.

User existingUser = session
	.LoadByUniqueConstraint<User>(x => x.Email, "john@gmail.com");

CheckForUniqueConstraints

Checks a document to see if its constraints are available on the server. It returns a UniqueConstraintCheckResult containing the loaded docs and properties they are responsible for.

User user = new User { Name = "John", Email = "john@gmail.com" };
UniqueConstraintCheckResult<User> checkResult = session.CheckForUniqueConstraints(user);

// returns whether its constraints are available
if (checkResult.ConstraintsAreFree())
{
	session.Store(user);
}
else
{
	User existingUser = checkResult.DocumentForProperty(x => x.Email);
}