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