【问题标题】:Use lists in a RealmObject on Xamarin在 Xamarin 上的 RealmObject 中使用列表
【发布时间】:2018-03-14 14:15:02
【问题描述】:

我在 Xamarin Forms 项目领域中使用。我有一个 A 类:

public class A: RealmObject
{
    [PrimaryKey]
    public string Id { get; set; }

    public string Name { get; set; }

    public A() : base()
    {
        Id= Guid.NewGuid().ToString();
        Name = $"Unknown_{Id}";
     }
}

还有一个包含 A 对象列表的 B 类:

public class B: RealmObject
{
    [PrimaryKey]
    public string Id{ get; set; }
    public string Name { get; set; }

    public IList<A> AList { get; }

    public B() : base()
    {
        Id= Guid.NewGuid().ToString();
        Name = $"Unknown_{Id}";
    }
}

IList Alist 包含已经保存在 Realm 上的对象,我想像引用一样保存它们。

问题是当我尝试在 Realm 上添加一个 B 对象时,我得到了异常:

Realms.Exceptions.RealmObjectManagedByAnotherRealmException:当对象已由另一个领域管理时,无法开始使用该领域管理对象

这个异常出现在下面代码的realm.Add(newB, update: true);

private void AddB(B b)
    {
        var realm = GetRealmInstance();

        using (var trans = realm.BeginWrite())
        {
            var newB = new B();
            newB.Name = b.Name;
            newB.Id = b.Id;

            foreach (var element in b.AList)
            {
                newB.Devices.Add(element);
            }

            realm.Add(newB, update: true);
            trans.Commit();
        });

        OnChanged?.Invoke();
    }

我必须明确指出 AList 中的所有对象都已保存在 Realm 上。

提前致谢。

【问题讨论】:

    标签: c# database xamarin xamarin.forms realm


    【解决方案1】:

    怎么样:

            var newB = new B();
            newB.Name = b.Name;
            newB.Id = b.Id;
    
            realm.Add(newB, update: true);
    
            foreach (var element in b.AList)
            {
                newB.Devices.Add(element);
            }
    
            trans.Commit();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-29
      • 2016-10-26
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      相关资源
      最近更新 更多