You are here: Advanced Features > Callbacks > Possible Usecases > Referential Integrity

Referential Integrity

db4o does not have a built-in referential integrity checking mechanism. Luckily EventRegistry gives you access to all the necessary events to implement it. You will just need to trigger validation on create, update or delete and cancel the action if the integrity is going to be broken.

For example, if Car object is referencing Pilot and the referenced object should exist, this can be ensured with the following handler in deleting() event:

private static void ReferentialIntegrityCheck(object sender,
                                              CancellableObjectEventArgs eventArguments)
{
    Object toDelete = eventArguments.Object;
    if (toDelete is Pilot)
    {
        IObjectContainer container = eventArguments.ObjectContainer();
        IEnumerable<Car> cars = from Car c in container
                                where c.Pilot == toDelete
                                select c;
        if (cars.Count() > 0)
        {
            eventArguments.Cancel();
        }
    }
}
CallbackExamples.cs: Referential integrity
Private Shared Sub ReferentialIntegrityCheck(ByVal sender As Object, ByVal eventArguments As CancellableObjectEventArgs)
    Dim toDelete As Object = eventArguments.Object
    If TypeOf toDelete Is Pilot Then
        Dim container As IObjectContainer = eventArguments.ObjectContainer()
        Dim cars As IEnumerable(Of Car) = From c As Car In container _
                                          Where c.Pilot Is toDelete
        If cars.Count() > 0 Then
            eventArguments.Cancel()
        End If
    End If
End Sub
CallbackExamples.vb: Referential integrity
IEventRegistry events = EventRegistryFactory.ForObjectContainer(container);
events.Deleting += ReferentialIntegrityCheck;
CallbackExamples.cs: Register handler
Dim events As IEventRegistry = EventRegistryFactory.ForObjectContainer(container)
AddHandler events.Deleting, AddressOf ReferentialIntegrityCheck
CallbackExamples.vb: Register handler

You can also add handlers for creating() and updating() events for a Car object to make sure that the pilot field is not null.

Note, that in client/server mode deleting event is only raised on the server side, therefore the code above can't be used and will throw an exception.