You are here: Platform Specific Issues > Disconnected Objects > Merging Changes > Wrong Approach

Wrong Approach

The wrong approach is to try to store disconnected objects. db4o manages object by their object-identity and doesn't recognize objects which have been serialized or loaded by another object container instance. This example shows, that instead of updating the object, db4o will store a new instance of the object.

Pilot joe;
using (IObjectContainer container = OpenDatabase())
{
    joe = QueryByName(container, "Joe");
}
// The update on another object 
joe.Name = "Joe New";
using (IObjectContainer otherContainer = OpenDatabase())
{
    otherContainer.Store(joe);
}
using (IObjectContainer container = OpenDatabase())
{
    // instead of updating the existing pilot,
    // a new instance was stored.
    IList<Pilot> pilots = container.Query<Pilot>();
    Console.WriteLine("Amount of pilots: " + pilots.Count);
    foreach (Pilot pilot in pilots)
    {
        Console.WriteLine(pilot);
    }
}
ObjectIdentityExamples.cs: Update doesn't works when using the different object containers
Dim joe As Pilot
Using container As IObjectContainer = OpenDatabase()
    joe = QueryByName(container, "Joe")
End Using
' The update on another object 
joe.Name = "Joe New"
Using otherContainer As IObjectContainer = OpenDatabase()
    otherContainer.Store(joe)
End Using
Using container As IObjectContainer = OpenDatabase()
    ' instead of updating the existing pilot,
    ' a new instance was stored.
    Dim pilots As IList(Of Pilot) = container.Query(Of Pilot)()
    Console.WriteLine("Amount of pilots: " & pilots.Count)
    For Each pilot As Pilot In pilots
        Console.WriteLine(pilot)
    Next
End Using
ObjectIdentityExamples.vb: Update doesn't works when using the different object containers

So in order to update an object, you need to load and store it in the same object-container. If you cannot do this, you need to merge to object-changes. See "Example Merge Changes"

using (IObjectContainer container = OpenDatabase())
{
    Pilot joe = QueryByName(container, "Joe");
    joe.Name = "Joe New";
    container.Store(joe);
}
using (IObjectContainer container = OpenDatabase())
{
    IList<Pilot> pilots = container.Query<Pilot>();
    Console.WriteLine("Amount of pilots: " + pilots.Count);
    foreach (Pilot pilot in pilots)
    {
        Console.WriteLine(pilot);
    }
}
ObjectIdentityExamples.cs: Update works when using the same object container
Using container As IObjectContainer = OpenDatabase()
    Dim joe As Pilot = QueryByName(container, "Joe")
    joe.Name = "Joe New"
    container.Store(joe)
End Using
Using container As IObjectContainer = OpenDatabase()
    Dim pilots As IList(Of Pilot) = container.Query(Of Pilot)()
    Console.WriteLine("Amount of pilots: " & pilots.Count)
    For Each pilot As Pilot In pilots
        Console.WriteLine(pilot)
    Next
End Using
ObjectIdentityExamples.vb: Update works when using the same object container