You are here: Advanced Features > Unique Constraints

Unique Constraints

Unique constraints allow a user to define a field to be unique across all the objects of a particular class stored to db4o. This means that you cannot save an object where a previously committed object has the same field value for fields marked as unique. A Unique Constraint is checked at commit-time and a constraint violation will cause a UniqueFieldValueConstraintViolationException to be thrown. This functionality is based on Commit-Time Callbacks feature.

How To Use Unique Constraints

First you need to add an index on the field which should be unique. After that you add the UniqueFieldValueConstraint to the configuration for the unique field.

configuration.Common.ObjectClass(typeof (UniqueId)).ObjectField("id").Indexed(true);
configuration.Common.Add(new UniqueFieldValueConstraint(typeof (UniqueId), "id"));
UniqueConstrainExample.cs: Add the index the field and then the unique constrain
configuration.Common.ObjectClass(GetType(UniqueId)).ObjectField("id").Indexed(True)
configuration.Common.Add(New UniqueFieldValueConstraint(GetType(UniqueId), "id"))
UniqueConstrainExample.vb: Add the index the field and then the unique constrain

After that, the unique constrain is applied. When you commit a transaction the uniqueness of the field is checked. If there's any violation, the UniqueFieldValueConstraintViolationException will be thrown.

container.Store(new UniqueId(42));
container.Store(new UniqueId(42));
try
{
    container.Commit();
}
catch (UniqueFieldValueConstraintViolationException e)
{
    Console.Out.WriteLine(e.StackTrace);
}
UniqueConstrainExample.cs: Violating the constrain throws an exception
container.Store(New UniqueId(42))
container.Store(New UniqueId(42))
Try
    container.Commit()
Catch e As UniqueFieldValueConstraintViolationException
    Console.Out.WriteLine(e.StackTrace)
End Try
UniqueConstrainExample.vb: Violating the constrain throws an exception