Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Sync Data

Partition-Based Sync - .NET SDK

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.

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.

The partition value determines which data the client application can access. You pass in the partition value when you open a synced realm.

Los pasos para abrir un realm sincronizado mientras estás en linea son:

  1. Your app code walks the user through authenticating.

  2. Create a PartitionSyncConfiguration object that includes the partition value and the User object.

  3. Abra un reino sincronizado llamando al método GetInstanceAsync() y pasando el PartitionSyncConfiguration objeto.

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);

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);
}

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.

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 partitionKey en 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 ownerId para 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.

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:

  1. Remove the automatically-generated subscriptions.

  2. Manually add the relevant subscriptions in your client codebase.

This enables you to see all of your subscription logic together in your codebase for future iteration and debugging.

For more information about the automatically-generated Flexible Sync subscriptions, refer to Migrate Client App to Flexible Sync.

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:

  1. Abre el realm existente.

  2. Crear una configuración para un nuevo reino.

  3. 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

Partition-Based Sync Only

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.

Volver

Stream Data to Atlas

En esta página