You are here: Platform Specific Issues > Disconnected Objects > Merging Changes > Example Merge Changes

Example Merge Changes

This example shows how changes are merged from the disconnected object to the object to update. To do this, traverse the object-graph and copy all value types over. All reference-types are first checked if they're an existing object. If it is,the primitives are copied over, otherwise it's a stored as a new object.

using (IObjectContainer container = OpenDatabase())
{
    // first get the object from the database
    Car carInDb = GetCarById(container, disconnectedCar.ObjectId);

    // copy the value-objects (int, long, double, string etc)
    carInDb.Name = disconnectedCar.Name;

    // traverse into the references
    Pilot pilotInDB = carInDb.Pilot;
    Pilot disconnectedPilot = disconnectedCar.Pilot;

    // check if the object is still the same
    if (pilotInDB.ObjectId.Equals(disconnectedPilot.ObjectId))
    {
        // if it is, copy the value-objects
        pilotInDB.Name = disconnectedPilot.Name;
        pilotInDB.Points = disconnectedPilot.Points;
    }
    else
    {
        // otherwise replace the object
        carInDb.Pilot = disconnectedPilot;
    }

    // finally store the changes
    container.Store(pilotInDB);
    container.Store(carInDb);
MergeExample.cs: merging
Using container As IObjectContainer = OpenDatabase()
    ' first get the object from the database
    Dim carInDb As Car = GetCarById(container, disconnectedCar.ObjectId)

    ' copy the value-objects (int, long, double, string etc)
    carInDb.Name = disconnectedCar.Name

    ' traverse into the references
    Dim pilotInDB As Pilot = carInDb.Pilot
    Dim disconnectedPilot As Pilot = disconnectedCar.Pilot

    ' check if the object is still the same
    If pilotInDB.ObjectId.Equals(disconnectedPilot.ObjectId) Then
        ' if it is, copy the value-objects
        pilotInDB.Name = disconnectedPilot.Name
        pilotInDB.Points = disconnectedPilot.Points
    Else
        ' otherwise replace the object
        carInDb.Pilot = disconnectedPilot
    End If

    ' finally store the changes
    container.Store(pilotInDB)
MergeExample.vb: merging

You can use reflection to automated this process. You can also use existing libraries like Automapper which help you to do this.