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

Change an Object Model - .NET SDK

Una migración transforma un reino existente y sus objetos de su estado actual. Versión del esquema de dominio a una más reciente. Los modelos de datos de las aplicaciones suelen cambiar con el tiempo para adaptarse a nuevos requisitos y funciones. Las migraciones le ofrecen la flexibilidad de actualizar automáticamente los datos de su aplicación existente cada vez que una aplicación cliente se actualiza a una versión más reciente.

Consideremos el siguiente ejemplo, en el que tenemos un RealmObject llamada "Persona":

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}

Supongamos que ahora queremos dividir la propiedad FullName en dos propiedades separadas, FirstName y LastName:

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

At this point, there is a mismatch between the model and any saved data, and an exception will be thrown when you try to open the realm.

The schema version identifies the state of a Realm Schema at some point in time. Realm tracks the schema version of each realm and uses it to map the objects in each realm to the correct schema.

Schema versions are integers that you may include in the realm configuration when you open a realm. If a client application does not specify a version number when it opens a realm then the realm defaults to version 0.

Importante

Increment Versions Monotonically

Migrations must update a realm to a higher schema version. Realm will throw an error if a client application opens a realm with a schema version that is lower than the realm's current version or if the specified schema version is the same as the realm's current version but includes different object schemas.

The following examples demonstrate how to add, delete, and modify properties in a schema. First, make the required schema change. Then, create a corresponding migration function to move data from the original schema to the updated schema.

Nota

Modify Schema Properties of a Synced Realm

The following page demonstrates how to modify schema properties of a local realm. Learn how to modify schema properties of a synced realm.

Nota

Versions Update on Realm Open

Assume that each schema change in this example occurs after an application has used each version for some amount of time. New schema version numbers only apply once you open the realm with an updated schema and explicitly specify the new version number, so in order to get to version 3, you would first need to open the app with versions 1 and 2.

A realm using schema version 1 has a Person object type:

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
}

El siguiente ejemplo añade una propiedad LastName al esquema Persona original:

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

The following example uses a combined FullName property instead of the separate FirstName and LastName property in the original Person schema:

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}

El siguiente ejemplo modifica la propiedad Age en el esquema original de Persona renombrándola a Birthday y cambiando el tipo a DateTimeOffset:

public partial class Person : IRealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
public string FullName { get; set; }
public DateTimeOffset Birthday { get; set; }
}

Tip

Bypass Migration During Development

When developing or debugging your application, you may prefer to delete the realm instead of migrating it. Use the ShouldDeleteIfMigrationNeeded flag to delete the database automatically when a schema mismatch would require a migration.

Nunca publique una aplicación en producción con esta marca configurada en true.

To migrate the realm to conform to the updated Person schema, set the realm's schema version to 4 and define a migration function to set the value of FullName based on the existing FirstName and LastName properties and the value of Birthday based on Age:

1var config = new RealmConfiguration
2{
3 SchemaVersion = 4,
4 MigrationCallback = (migration, oldSchemaVersion) =>
5 {
6 var oldVersionPeople = migration.OldRealm.DynamicApi.All("Person");
7 var newVersionPeople = migration.NewRealm.All<Person>();
8
9 // Migrate Person objects
10 for (var i = 0; i < newVersionPeople.Count(); i++)
11 {
12 var oldVersionPerson = oldVersionPeople.ElementAt(i);
13 var newVersionPerson = newVersionPeople.ElementAt(i);
14
15 // Changes from version 1 to 2 (adding LastName) will
16 // occur automatically when Realm detects the change
17
18 // Migrate Person from version 2 to 3:
19 // Replace FirstName and LastName with FullName
20 // LastName doesn't exist in version 1
21 var firstName = oldVersionPerson.DynamicApi.Get<string>("FirstName");
22 var lastName = oldVersionPerson.DynamicApi.Get<string>("LastName");
23
24 if (oldSchemaVersion < 2)
25 {
26 newVersionPerson.FullName = firstName;
27 }
28 else if (oldSchemaVersion < 3)
29 {
30 newVersionPerson.FullName = $"{firstName} {lastName}";
31 }
32
33 // Migrate Person from version 3 to 4: replace Age with Birthday
34 if (oldSchemaVersion < 4)
35 {
36 var birthYear =
37 DateTimeOffset.UtcNow.Year - oldVersionPerson.DynamicApi.Get<int>("Age");
38 newVersionPerson.Birthday =
39 new DateTimeOffset(birthYear, 1, 1, 0, 0, 0, TimeSpan.Zero);
40 }
41 }
42 }
43};
44var realm = Realm.GetInstance(config);

Volver

relación

En esta página