【问题标题】:How to clone object with a different Primary Key如何使用不同的主键克隆对象
【发布时间】: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);
});

【问题讨论】:

    标签: c# .net realm


    【解决方案1】:

    我不确定App.RealmDB 在幕后做了什么,但是使用开箱即用的 Realm 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
    

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 1970-01-01
      • 2013-07-17
      • 2017-01-18
      • 2018-12-19
      • 2010-11-08
      • 2012-11-17
      • 2010-09-07
      • 2012-12-07
      相关资源
      最近更新 更多