【发布时间】: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