【发布时间】:2017-06-07 01:39:03
【问题描述】:
我有这个类 Cart_Record,如下所示。我想更新主键。为此,我试图将对象克隆到一个新对象中以复制 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);
});
【问题讨论】: