Best practice for avoiding Permission duplication after realm.Add(newVersion, update: true)


I noticed some problem with object level permissions. When using realm.Add(object, update: true) object in database is updated if exist, but permissions objects are duplicated.

syncRealm.Add(newVersion, true);

var permission = Permission.Get(user.Role, newVersion);
permission.CanRead = true;
permission.CanUpdate = true;
permission.CanDelete = true;
permission.CanSetPermissions = false;

The only solution I have for now is to check before Add if object with same PrimaryKey already exist and don’t set permissions if only update is expected, but it seems to be not very elegant.

Is there any better way to do it? How to prevent realm from crating new permission set for same object and same role?


Hm… I have not run a test to verify it, but looking at the code, I am surprised you end up with duplicate entries. Unless I’m missing something, when you call syncRealm.Add(newVersion, true), the permissions from the old version will be cleared, because they are just a list of objects and the way .Add(update: true) works is that it will replace the content of all lists in the old object with the values passed in the new object. If I correctly assume that newVersion doesn’t have any permissions defined, I would expect that after executing .Add, it will end up with an empty Permissions collection. Then, calling Permission.Get will actually create a new object and add it to that collection, meaning that you end up with a single permission object associated with newVersion.

Now, with all that being said, because there are no cascading deletes in Realm, the permissions, associated with oldVersion will just exist in the void, disassociated from their parent object and essentially being dead baggage. Unfortunately there’s no way to prevent that at the moment short of assigning them to newVersion:

var oldVersion = syncRealm.Find<Something>(newVersion.Id);
foreach (var perm in oldVersion.Permissions)

syncRealm.Add(newVersion, true);


With this workaround, when calling Permission.Get, you’ll actually get the existing permission, this time, associated with newVersion, so you won’t create an extra object.


Thank you for explanation and hint.