Primary key after sync


#1

I’m trying to figure out how to deal with situations where objects are created in a mobile device Realm while the device is offline and a primary key has to be generated locally. Then later when ROS syncs to the main RDBMS, that database will generate its own PK based on its auto increment. However, I cannot change that PK on Realm. I’ve tried using an optional field for the PK in realm, but that only allows a single record with a NULL PK which will not work.

How is this generally handled? Thank you!


#2

Why dont you use the realms PK? If you dont use auto increment pk on the other side, you dont have this issue.


#3

We’re bolting Realm onto a large existing application that already has hundreds of tables and a complex web application associated with it. These tables have been in use for a long time and changing them is pretty much prohibitive. We are sync’ing a subset of data to ROS for mobile users to get a subset of features they need to access in the field (offline, etc).

So when those users now create new objects we need to get those into the main database. If we generated a random ID on the mobile device and used that as the main PK we are concerned about future collisions.


#4

You can store the two keys in separate properties. Your model could be something like:

class MyModel
{
    [PrimaryKey]
    public string RealmId { get; private set; } = Guid.NewGuid().ToString();

    [Indexed] // If needed to do quick lookups by db id
    public long? DbId { get; private set; }
}

Then your devices will insert objects while offline with a unique RealmId. Then, when those objects get synced and transferred to your main db, you can populate the Realm model’s DbId field. Obviously, one downside is that Realm will no longer enforce uniqueness for the DbId field, but if you’re only assigning these values server-side after syncing up with your main db, that should be fine.