2017-06-07 52 views
0

我有這個類Cart_Record,如下所示。我想更新PrimaryKey。要做到這一點,我試圖克隆對象到一個新的對象來複制CartLines和更新ID。我沒有在問題隊列或文檔中找到很多幫助我的東西。如何用不同的主鍵克隆對象

public class Cart_Record : RealmObject 
{ 
    public Cart_Record() { } 

    public Cart_Record(IList<Cart_Line> cartLines, int id) 
    { 
     ID = id; 
     foreach (var cartLine in cartLines) 
      CartLines.Add(App.RealmDB.Find<Cart_Line>(cartLine.ProductId)); 
    } 

    [PrimaryKey] 
    public int ID { get; set; } 

    public IList<Cart_Line> CartLines { get; } 
} 

我想這

var appCart = App.RealmDB.All<Cart_Record>().First(); 

App.RealmDB.Write(() => 
{ 
    var cartLines = new List<Cart_Line>(appCart.CartLines); 
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID)); 
    App.RealmDB.Add<Cart_Record>(new Cart_Record(cartLines, serverCart.ID)); 
}); 

不過,我不斷收到異常,特別是RealmObjectManagedByAnotherRealmException。我不明白怎麼樣,因爲我沒有將Cart_Line對象讀到Realm中,只是讀取新對象中的CartLine列表。

我在做什麼錯?

提前致謝。

編輯:我發現了一些可行的,但我想看看別人是否有更好的方法。這對我來說很有用。

var appCart = App.RealmDB.All<Cart_Record>().First();      
App.RealmDB.Write(() => 
{ 
    var cartLines = new List<Cart_Line>(appCart.CartLines); 
    App.RealmDB.Remove(App.RealmDB.Find<Cart_Record>(appCart.ID)); 
    var newAppCart = App.RealmDB.Add<Cart_Record>(new Cart_Record() { ID = serverCart.ID }); 
    foreach (var cartLine in cartLines) 
     newAppCart.CartLines.Add(cartLine); 
}); 

回答

1

我不知道什麼App.RealmDB做引擎蓋下,但使用外的開箱王國API,要實現可以通過簡單地從原來的加入CartLines到做什麼更新對象:

// Assume want to change Id from 1 to 2 
var realm = Realm.GetInstance(); 
var original = realm.Find<Cart_Record>(1); 

var updated = new Cart_Record { ID = 2 }; // other properties must be copied here 
foreach (var cart in original.CartLines) 
{ 
    updated.CartLines.Add(cart); 
} 

realm.Write(() => 
{ 
    realm.Remove(original); 
    realm.Add(updated); 
}); 

// updated now has all the original's CartLines