简体   繁体   中英

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. And I had a problem when used to realm.Add(obj, update) statement. 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. 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.

            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. Some of these objects had a property pointing to a custom User object, which I was naively assigning in the object's constructor.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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