Android: Change old primary key in realm migration

亡梦爱人 提交于 2019-12-06 06:39:23

问题


Can I change old primary key with new primary key in realm migration script?


回答1:


Yes, it is possible.

        RealmObjectSchema objectSchema = schema.get("MyObject");
        objectSchema.addField("newId", long.class)
                .transform(new RealmObjectSchema.Function() {
                    @Override
                    public void apply(DynamicRealmObject obj) {
                        obj.setLong("newId", getNewId(obj));
                    }
                })
                .removeField("id")
                .renameField("newId", "id")
                .addPrimaryKey("id");

However, you can't directly create the field as

objectSchema.addField("newId", long.class, FieldAttribute.PRIMARY_KEY)

because the values are initialized to 0 in your database, which means you'll be violating the constraint on creation. So you must add the primary key constraint only after the values are set.


In your case,

RealmObjectSchema objectSchema = schema.get("MyObject");
objectSchema.addField("newId", long.class)
    .transform(new RealmObjectSchema.Function() {
        @Override
        public void apply(DynamicRealmObject obj) {
            obj.setLong("newId", getNewId(obj));
        }
    })
    .removePrimaryKey()
    .addPrimaryKey("newId");


来源:https://stackoverflow.com/questions/40999518/android-change-old-primary-key-in-realm-migration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!