Partition-Based Sync es un modo más antiguo para usar Atlas Device Sync con el SDK de Realm .NET. Recomendamos usar Flexible Sync para nuevas aplicaciones. La información en esta página es para usuarios que aún utilizan Partition-Based Sync.
Tip
El SDK de Realm .NET v11.1.0 y versiones posteriores permiten migrar de la sincronización basada en particiones a la sincronización flexible. Para obtener más información, consulte: Migrar de la sincronización basada en particiones a la sincronización flexible. Recomendamos migrar las aplicaciones antiguas de sincronización basada en particiones para usar la sincronización flexible.
valor de la partición
Cuando se selecciona Partition-Based Sync para la configuración de la aplicación de backend, la implementación del cliente debe incluir un valor de la partición. Este es el valor del campo clave de partición que se selecciona al configurar la Partition-Based Sync.
El valor de la partición determina a qué datos puede acceder la aplicación cliente. Se pasa el valor de la partición al abrir un dominio sincronizado.
Open a Partition-Based Sync Realm While Online
Los pasos para abrir un realm sincronizado mientras estás en linea son:
Your app code walks the user through authenticating.
Create a PartitionSyncConfiguration object that includes the partition value and the User object.
Abra un reino sincronizado llamando al método GetInstanceAsync() y pasando el
PartitionSyncConfigurationobjeto.
El siguiente código demuestra estos pasos:
user = await app.LogInAsync( Credentials.EmailPassword("caleb@mongodb.com", "MySekritPwd")); config = new PartitionSyncConfiguration("myPart", user); try { realm = await Realm.GetInstanceAsync(config); } catch (Exception ex) { Console.WriteLine($@"Error creating or opening the realm file. {ex.Message}"); }
In the above example, the code shows how to open the realm asynchronously by calling GetInstanceAsync(). You can also open a realm synchronously by calling the GetInstance() method:
var synchronousRealm = Realm.GetInstance(config);
Open a Partition-Based Sync Realm While Offline
Once a user authenticates, the User object persists on the device until the user logs off. This allows your app to retrieve an existing user and open a synced realm in an offline state. Changes that occur while offline will be synced by the SDK once the device reconnects to your App.
El siguiente código muestra cómo comprobar si existe un objeto User. Si no hay ninguno, utiliza el proceso que se indica arriba para obtener un usuario. Si el dispositivo ya tiene un user, se abre el realm sincronizado con ese usuario:
if (app.CurrentUser == null) { // App must be online for user to authenticate user = await app.LogInAsync( Credentials.EmailPassword("caleb@mongodb.com", "MySekritPwd")); config = new PartitionSyncConfiguration("_part", user); realm = await Realm.GetInstanceAsync(config); } else { // This works whether online or offline user = app.CurrentUser; config = new PartitionSyncConfiguration("_part", user); realm = Realm.GetInstance(config); }
Migrate from Partition-Based Sync to Flexible Sync
You can migrate your App Services Device Sync Mode from Partition-Based Sync to Flexible Sync. Migrating is an automatic process that does not require any changes to your application code. Automatic migration requires Realm .NET SDK version 11.1.0 or newer.
Migrating enables you to keep your existing App Services users and authentication configuration. Flexible Sync provides more versatile permissions configuration options and more granular data synchronization.
For more information about how to migrate your App Services App from Partition-Based Sync to Flexible Sync, refer to Migrate Device Sync Modes.
Actualizar el código de cliente después de la migración
The automatic migration from Partition-Based Sync to Flexible Sync does not require any changes to your client code. However, to support this functionality, Realm automatically handles the differences between the two Sync Modes by:
Automatically creating Flexible Sync subscriptions for each object type where
partitionKey == partitionValue.Inyectar un campo
partitionKeyen cada objeto si aún no existe uno. Esto es necesario para la suscripción automática de Flexible Sync.
Si necesitas realizar actualizaciones en el código cliente después de la migración, considera actualizar tu base de código cliente para remover funcionalidades ocultas de migración. Tal vez quieras actualizar tu base de código de cliente cuando:
Agregue un nuevo modelo o cambie un modelo en su base de código de cliente.
You add or change functionality that involves reading or writing Realm objects
Quieres implementar un control más específico sobre los datos que sincronizas
Make these changes to convert your Partition-Based Sync client code to use Flexible Sync:
Cambia tu PartitionSyncConfiguration a una FlexibleSyncConfiguration.
Agrega propiedades relevantes a tus modelos de objetos para usarlas en tus suscripciones de Flexible Sync. Por ejemplo, podrías agregar una propiedad
ownerIdpara permitir que un usuario sincronice solo sus propios datos.Remove automatic Flexible Sync subscriptions and manually create the relevant subscriptions.
For examples of Flexible Sync permissions strategies, including examples of how to model data for these strategies, refer to Device Sync Permissions Guide.
Remove and Manually Create Subscriptions
When you migrate from Partition-Based Sync to Flexible Sync, Realm automatically creates hidden Flexible Sync subscriptions for your app. The next time you add or change subscriptions, we recommend that you:
Esto le permite ver toda su lógica de suscripción junta en su base de código para futuras iteraciones y depuraciones.
For more information about the automatically-generated Flexible Sync subscriptions, refer to Migrate Client App to Flexible Sync.
Migrar de dominios no sincronizados a dominios sincronizados
Puedes convertir un dominio no sincronizado en uno sincronizado (con sincronización basada en particiones). Para convertir un dominio no sincronizado en uno con sincronización basada en particiones, sigue estos pasos:
Abre el realm existente.
Crear una configuración para un nuevo reino.
Llame al método WriteCopy() en el reino existente para copiar los datos al nuevo reino.
In the following code, we open a non-synced realm, create a new PartitionSyncConfiguration object and then copy the existing realm to the new realm. We then delete the existing realm and open the new realm.
var existingConfig = new RealmConfiguration("example.realm"); var existingRealm = Realm.GetInstance(existingConfig); var app = App.Create("my-app-id"); var user = await app.LogInAsync( Credentials.EmailPassword("email@example.com", "password")); var syncConfig = new PartitionSyncConfiguration("user_partition", user); existingRealm.WriteCopy(syncConfig); // You can now delete the nonsynced realm: Realm.DeleteRealm(existingConfig); // You can now use the synced realm: var syncedRealm = Realm.GetInstance(syncConfig);
Nota
Solo sincronización basada en particiones
This method only supports converting between a non-sync realm and Partition-Based Sync. If your app uses Flexible Sync, you must manually iterate through the objects in one realm and copy them into the other realm.