views:

355

answers:

1
+1  Q: 

Db4o object update

Hi,

I'm using db4o for a simple app, with an embedded db. When I save an object, and then change the object, is it suppose that db4o returns the changed object?

Here's the code:

[Test]
    public void NonReferenceTest()
    {
      Aim localAim = new Aim("local description", null);
      dao.Save(localAim);

      // changing the local value should not alter what we put into the dao
      localAim.Description = "changed the description";

      IQueryable<Aim> aims = dao.FindAll();

      var localAim2 = new Aim("local description", null);
      Assert.AreEqual(localAim2, aims.First());
    }

The test fails. Do I need to setup the db4o container in any special way? wrap it in commit calls? Thanks

+1  A: 

Actually, it is supposed to work that way. You have to keep in mind that you are manipulating objects not only data.

When storing (or querying) an object to (or from) the object-database, it keeps the link between the stored data and the object in memory. This is needed when you update the object and store it in the database. You actually do not want that a new object is stored but you want the old object to be updated. So, when retrieving an object that still exists in memory, you will be given a reference to that object.

Another reason is data integrity. Look at your code again, and imagine it gives you the data of the database and not a reference to the updated object:

Aim localAim = new Aim("local description", null);
dao.Save(localAim);

// changing the local value should not alter what we put into the dao
localAim.Description = "changed the description";

IQueryable<Aim> aims = dao.FindAll();

var localAim2 = aims.First();

// Assuption A: localAim2 != localAim
localAim2.Description += " added s/t";

dao.Save(localAim); 
// with Assuption A you now have "changed the description" in database
dao.Save(localAim2);
// with Assuption A you now have "local description added s/t"

The problem with Assuption A (localAim2 != localAim) is that you work on the same object that is stored in the database with 2 different contents. Without Assuption A (i.e., localAim2 == localAim), your data is allways consistent since you have only one object (referenced two times).

mr_georg