How To Use Unique Constraints

In order to work with the unique constraints you will need to remember the following 3 steps.

1. Add an index for a field you wish to be unique:

c#:

configuration.ObjectClass(typeof(Item)).ObjectField("field").Indexed(true);

VB:

configuration.ObjectClass(GetType(Item)).ObjectField("field").Indexed(true)



2. Configure a unique constraint:

c#:

configuration.Add(new UniqueFieldValueConstraint(typeof(Item), "field"));

VB:

configuration.Add(New UniqueFieldValueConstraint(GetType(Item), "field"))



3. Handle unique constraint violation:

c#:
// open objectContainer
try {
  // do some work and save some objects
  objectContainer.Commit();
} catch(UniqueFieldValueConstraintViolationException ex) {

  // log the error, notify the user
  objectContainer.Rollback();
}

VB:
// open objectContainer
Try
  // do some work and save some objects
  objectContainer.Commit()
Catch ex As UniqueFieldValueConstraintViolationException

  // log the error, notify the user
  objectContainer.Rollback()
End Try