Resolving RealmException in Nested Model Updates

I have a model called Violation, which contains a list of model Comments, and each Comment is associated with a Profile.

When I need to save a new Violation but the Profile already exists, I can follow the procedure below:

_realm.write(() {
_realm.add(violation, update: true);
});

The ‘update’ flag handles any potential conflicts.

However, when I want to update a Violation with a new Comment, I encounter an exception when I try the following:

_realm.write(() {
violation.comments.add(comment);
});

The exception message reads:

RealmException: Error setting value at index 0. Error: RealmException: Error setting property Comment.addedBy Error: RealmException: Attempting to create an object of type ‘Profile’ with an existing primary key value ‘“e5646d16-0c89-5a73-b473-cdbf20b0fda1”’. Error code: 1013.

Hmm. Perhaps I am not understanding the meaning but handling conflicts is not the purpose of the update flag. It’s purpose is to provide an upsert: If the object does not exist, it is created. If it exists, it updates it’s properties.

The other cade is correct so we would need to see what those objects look like but it’s likely something to do with Profile or potentially some issue with a duplicate violation object.

The problem is that the list API doesn’t have mechanism to supply an update parameter. This means that if you want to add an unmanaged (i.e. one not obtained from Realm) object, it will first try to add it to the database (equivalent to realm.add(update: false)), which will error out if there’s already a comment with the same primary key. If you want to upsert the comment, you’d need to manually add it to the Realm before adding it to the list:

realm.add(comment, update: true);
violation.comments.add(comment);

My wording is off, sorry. I meant that when I am creating a Violation which is related to a Profile that exists, the creation happens when I have set update to true. I am not sure what to do when updating a Violation as per the second piece of code. The Comment has an existing profile and I am wondering how to flag with update to avoid exception as in the question.

I assume a new Comment was an unmanaged comment that doesn’t exist in Realm and has a unique primary key? If not @nirinchev response may be the answer

Is the comment being added to Realm before being added to the comments (comments.add) or is this an unmanaged object that does not exist Realm (in which the code should work…at least it does for us)

The new Comment was unmanaged and had a Profile that existed in Realm. I am now saving the comment as advised by @nirinchev and it works.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.