简体   繁体   English

如何异常解决:“如果对象已由另一个领域管理,则无法开始管理该领域的对象”

[英]How to resolve with a exception “Cannot start to manage an object with a realm when it's already managed by another realm”

I'm using Realm Mobile Database in my Xamarin project. 我在Xamarin项目中使用Realm Mobile Database。 And I had a problem when used to realm.Add(obj, update) statement. 当我使用realm.Add(obj,update)语句时,我遇到了一个问题。 It throw a exception "Cannot start to manage an object with a realm when it's already managed by another realm". 它引发异常“当已经由另一个领域管理的对象时,无法开始管理该对象”。 What I didn't see on Swift version on same a demo. 我在同一演示中的Swift版本上没有看到的内容。 I knew when realm object's IsManage is true, and I added a object exist in realm to a another object for update then throw that exception, so how I can update a realm object with a member what exist before that. 我知道领域对象的IsManage为true的时候,然后将领域中存在的对象添加到另一个对象中以进行更新,然后抛出该异常,因此如何使用成员之前存在的成员来更新领域对象。

            var objUpdate = new AccountAccessDB()
            {
                Id = this.Id, //Id is PrimaryKey
                User = this.User // this object existed
            }; 
            objUpdate.something.Add(new Object()) // this is that I want to update.

            realm.Write(() => {
                realm.Add(objUpdate, true);
            });

Thanks! 谢谢!

It looks like you're opening to different realms and then try to add an object from one realm to the other realm. 看起来您正在打开不同的领域,然后尝试将一个对象从一个领域添加到另一个领域。

Remember that realm is unique by it's configuration, so if you pass a configuration when opening a realm, you have to use an identical configuration when trying to open the same realm. 请记住,领域是通过其配置来唯一的,因此,如果在打开领域时通过配置,则在尝试打开同一领域时必须使用相同的配置。

// First time you open realm
var realm = Realm.GetInstance("my.realm");
...

// Somewhere else in your code
var realm = Realm.GetInstance(); // <== This is not the same realm!
var myRealm = Realm.GetInstance("my.realm"); // <== This is the same realm

I recently came across the same issue and managed to find the issue. 我最近遇到了同一问题,并设法找到了问题。

In my case, I was importing a large amount of unmanaged objects to Realm. 就我而言,我正在将大量非托管对象导入Realm。 Some of these objects had a property pointing to a custom User object, which I was naively assigning in the object's constructor. 这些对象中的某些对象具有指向自定义User对象的属性,我是在该对象的构造函数中天真地为其分配的。

Naturally this means that I was trying to import unmanaged objects that had a property which was pointing to a managed object (created in a different instance, too). 自然地,这意味着我试图导入具有指向托管对象的属性的非托管对象(也创建于另一个实例中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM