2009-09-04 129 views
1

我正在使用db4o作爲一個簡單的應用程序,並帶有嵌入式數據庫。當我保存一個對象,然後更改該對象時,是否假設db4o返回已更改的對象?Db4o對象更新

下面的代碼:

[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()); 
    } 

測試失敗。我需要以任何特殊方式安裝db4o容器嗎?將它包裝在提交調用中?由於

回答

1

事實上,它應該是這樣的。你必須記住,你操縱的不僅僅是數據對象。

當存儲(或查詢)的對象(或從)對象的數據庫,它保持所存儲的數據和在存儲器中的對象之間的鏈接。當您更新對象並將其存儲在數據庫中時,這是需要的。您實際上不希望存儲新對象,但希望舊對象得到更新。 因此,當檢索一個仍然存在於內存中的對象時,您將被賦予對該對象的引用。

另一個原因是數據完整性。再看看你的代碼,並想象它給你的數據庫的數據,而不是一個參考更新的對象:

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" 

與Assuption A(!localAim2 = localAim)的問題是,你在同一個工作對象,它以2個不同的內容存儲在數據庫中。 如果沒有Assuption A(即localAim2 == localAim),您的數據總是一致的,因爲您只有一個對象(引用兩次)。