Create an Object Model
Realm classes are regular C# classes that define the Realm schema.
Importante
Herencia
Todos los objetos de Realm heredan del
Interfaz IRealmObject, IEmbeddedObject o IAsymmetricObject y debe declararse partial clases.
En versiones del SDK de .NET anteriores 10.18.0 a, los objetos derivan de las clases base RealmObject, EmbeddedObject o AsymmetricObject. Este enfoque para la definición del modelo Realm aún se admite, pero no incluye nuevas funciones como las anotaciones de nulabilidad. En una futura versión del SDK, las clases base quedarán obsoletas. Debe usar las interfaces para cualquier clase nueva que escriba y considerar la migración de las clases existentes.
Nota
Class names are limited to a maximum of 57 UTF-8 characters.
Object Schema
An object schema is a configuration object that defines the properties and relationships of a Realm object. Realm client applications define object schemas with the native class implementation in their respective language using the Object Schema.
Los esquemas de objetos especifican restricciones sobre las propiedades de un objeto, como el tipo de datos de cada propiedad y si una propiedad es obligatoria o no. Los esquemas también pueden definir relaciones entre tipos de objetos en un realm.
Cada aplicación tiene un Esquema de Servicios de Aplicaciones formado por una lista de esquemas de objetos para cada tipo de objeto que pueden contener los reinos en esa aplicación. Realm garantiza que todos los objetos en un realm cumplan con el esquema para su tipo de objeto Realm y valida los objetos cuando se crean, modifican o eliminan.
Property Annotations
Las propiedades del esquema son propiedades estándar de C# en un RealmObject. Existen varias anotaciones de la propiedad que puedes usar para definir con mayor precisión cómo un Realm gestiona una propiedad específica.
llave primaria
A primary key is a property that uniquely identifies an object. You can create a primary key with any of the following types (or their nullable counterparts):
ObjectIdUUIDstringcharbyteshortintlong
You may define a primary key on a single property for an object type as part of the object schema. Realm automatically indexes primary key properties, which allows you to efficiently read and modify objects based on their primary key.
If an object type has a primary key, then all objects of that type must include the primary key property with a value that is unique among objects of the same type in a realm.
Nota
Once you assign a property as a primary key, you cannot change it.
The following example demonstrates how to designate a primary key in an object schema:
public partial class Dog : IRealmObject { [] public string Name { get; set; } public int Age { get; set; } public Person? Owner { get; set; } }
Indexes
Los índices mejoran significativamente el tiempo de las queries en un Realm. Sin índices, Realm analiza cada documento en una colección para seleccionar los documentos que coinciden con la query dada. Sin embargo, si existe un índice aplicable para una query, Realm utiliza el índice para limitar la cantidad de documentos que debe inspeccionar.
You can index properties with the following types:
boolbyteshortintlongDateTimeOffsetcharstringObjectIdUUID
Nota
Adding an index speeds up queries at the cost of slightly slower write times and additional storage and memory overhead. Indexes require space in your realm file, so adding an index to a property increases disk space consumed by your realm file. Each index entry is a minimum of 12 bytes.
Para indexar una propiedad, utilice el atributo Indexed. Con el Indexed atributo, puede especificar el tipo de índice de la propiedad mediante la enumeración IndexType. En el siguiente ejemplo, tenemos un índice predeterminado ("General") en la Name propiedad:
public partial class Person : IRealmObject { [] public string Name { get; set; } [] public string Biography { get; set; } }
Nota
Cuando se crea un índice, este se crea en el realm local y no en una colección de Atlas. Si se necesita realizar queries directamente en una colección de Atlas y se desea mejorar el rendimiento, consulte Crear, ver, descartar y ocultar índices.
Full-Text Search Indexes
Además de los índices estándar, Realm también admite índices de texto completo (FTS) en string propiedades. Aunque es posible query un campo de string con o sin un índice estándar, un índice FTS permite buscar varias palabras y frases y excluir otras.
Para obtener más información sobre cómo consultar índices de texto completo, consulta Búsqueda de texto completo (LINQ) y Búsqueda de texto completo (RQL).
Para indexar una propiedad FTS, utiliza el atributo Indexed con la enumeración IndexType.FullText. En el siguiente ejemplo, tenemos un índice FullText en la propiedad Biography:
public partial class Person : IRealmObject { [] public string Name { get; set; } [] public string Biography { get; set; } }
Default Field Values
You can use the built-in language features to assign a default value to a property. In C#, you can assign a default value on primitives in the property declaration. You cannot set a default value on a collection, except to set it to null!. Even if you set a collection to null!, collections are always initialized on first access, so will never be null.
public partial class Person : IRealmObject { public string Name { get; set; } = "foo"; public IList<PhoneNumber> PhoneNumbers { get; } = null!; }
Nota
Valores por defecto y anulabilidad
Aunque los valores predeterminados aseguran que un objeto recién creado no pueda contener un valor de null (a menos que se especifique un valor predeterminado de null), no afectan la posibilidad de nulidad de una propiedad. Para hacer que una propiedad no sea anulable, consulta Propiedades requeridas.
Ignorar una propiedad
If you don't want to save a property in your model to a realm, you can ignore that property. A property is ignored by default if it is not autoimplemented or does not have a setter.
Ignore a property from a Realm object model with the Ignored attribute:
// Rather than store an Image in Realm, // store the path to the Image... public string ThumbnailPath { get; set; } // ...and the Image itself can be // in-memory when the app is running: [] public Image? Thumbnail { get; set; }
Rename a Property
Por defecto, Realm utiliza el nombre definido en la clase de modelo para representar internamente las propiedades. En algunos casos, es posible que desees cambiar este comportamiento:
Para facilitar el trabajo en todas las plataformas, ya que las convenciones de nomenclatura difieren.
To change a property name in .NET without forcing a migration.
Choosing an internal name that differs from the name used in model classes has the following implications:
Las migraciones deben utilizar el nombre interno al crear clases y propiedades.
Los errores de esquema reportados utilizarán el nombre interno.
Use the [MapTo] attribute to rename a property:
public partial class Person : IRealmObject { [] public string Name { get; set; } }
Rename a Class
Por defecto, Realm utiliza el nombre definido en la clase del modelo para representar internamente las clases. En algunos casos, es posible que desees cambiar este comportamiento:
To support multiple model classes with the same simple name in different namespaces.
Para facilitar el trabajo en todas las plataformas, ya que las convenciones de nomenclatura difieren.
To use a class name that is longer than the 57 character limit enforced by Realm.
Cambiar el nombre de una clase en .NET sin forzar una migración.
Use the [MapTo] attribute to rename a class:
[] public partial class Person : IRealmObject { public string Name { get; set; } }
Custom Setters
Realm will not store a property with a custom setter. To use a custom setter, store the property value in a private property and then map that value to a public property with the custom setter. Realm will store the private property, while you modify its value via the public property. In the following code, the private email property is stored in the realm, but the public Email property, which provides validation, is not persisted:
// This property will be stored in the Realm private string email { get; set; } // Custom validation of the email property. // This property is *not* stored in Realm. public string Email { get { return email; } set { if (!value.Contains("@")) throw new Exception("Invalid email address"); email = value; } }
Define Unstructured Data
Nuevo en la versión 12.2.0.
Starting in SDK version 12.2.0, you can store collections of mixed data within a RealmValue property. You can use this feature to model complex data structures, such as JSON or MongoDB documents, without having to define a strict data model.
Unstructured data is data that doesn't easily conform to an expected schema, making it difficult or impractical to model to individual data classes. For example, your app might have highly variable data or dynamic data whose structure is unknown at runtime.
Storing collections in a mixed property offers flexibility without sacrificing functionality, including performant synchronization when using Device Sync. And you can work with them the same way you would a non-mixed collection:
Se pueden anidar colecciones mixtas hasta 100 niveles.
You can query on and react to changes on mixed collections.
You can find and update individual mixed collection elements.
However, storing data in mixed collections is less performant than using a structured schema or serializing JSON blobs into a single string property.
Para modelar datos no estructurados en su aplicación, defina las propiedades adecuadas en su esquema como tipos RealmValue. A continuación, puede configurar estas RealmValue propiedades como una lista o un diccionario de RealmValue elementos. Tenga en cuenta que RealmValue no puede representar un conjunto ni un objeto incrustado.
Tip
Use a map of mixed data types when the type is unknown but each value will have a unique identifier.
Utilice una lista de tipos de datos mixtos cuando el tipo sea desconocido, pero el orden de los objetos sea importante.
Omitir clases de su esquema de reino
De forma predeterminada, el esquema de dominio de su aplicación incluye todas las clases que implementan IRealmObject o IEmbeddedObject. Si solo desea incluir un subconjunto de estas clases en su esquema de dominio, puede actualizar su configuración para incluir las clases específicas que desee:
// Declare your schema partial class LoneClass : IRealmObject { public string Name { get; set; } } class AnotherClass { private void SetUpMyRealmConfig() { // Define your config with a single class var config = new RealmConfiguration("RealmWithOneClass.realm"); config.Schema = new[] { typeof(LoneClass) }; // Or, specify multiple classes to use in the Realm config.Schema = new[] { typeof(Dog), typeof(Cat) }; } }
Required and Optional Properties
En C#, los tipos de valor, como int booly, no admiten valores nulos de forma implícita. Sin embargo, pueden hacerse opcionales mediante la notación de signo de? interrogación ().
A partir de C# 8.0, se introdujeron tipos de referencia anulables. Si tu proyecto utiliza C# 8.0 o posterior, también puedes declarar tipos de referencia, como string y byte[], como anulables con ?.
Nota
A partir de .NET 6.0, el contexto anulable está habilitado por defecto para los proyectos nuevos. Para proyectos antiguos, puedes activarlo manualmente. Para obtener más información, consulta https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types#setting-the-nullable-context.
The Realm .NET SDK fully supports the nullable-aware context and uses nullability to determine whether a property is required or optional. The SDK has the following rules:
Realm assumes that both value- and reference-type properties are required if you do not designate them as nullable. If you designate them as nullable by using
?, Realm considers them optional.You must declare properties that are Realm object types as nullable.
No se pueden declarar colecciones (listas, conjuntos, vínculos de retroceso y diccionarios) como anulables, pero sus parámetros pueden ser anulables de acuerdo con las siguientes reglas:
For all types of collections, if the parameters are primitives (value- or reference-types), they can be required or nullable.
For lists, sets, and backlinks, if the parameters are Realm objects, they cannot be nullable.
For dictionaries with a value type of Realm object, you must declare the value type parameter as nullable.
El siguiente fragmento de código demuestra estas reglas:
public partial class Person : IRealmObject { /* Reference Types */ public string NonNullableName { get; set; } public string? NullableName { get; set; } public byte[] NonNullableArray { get; set; } public byte[]? NullableArray { get; set; } /* Value Types */ public int NonNullableInt { get; set; } public int? NullableInt { get; set; } /* Realm Objects */ public Dog? NullableDog { get; set; } // public Dog NonNullableDog { get; set; } // Compile-time error /* Collections of Primitives */ public IList<int> IntListWithNonNullableValues { get; } public IList<int?> IntListWithNullableValues { get; } // public IList<int>? NullableListOfInts { get; } // Compile-time error /* Collections of Realm Objects */ public IList<Dog> ListOfNonNullableObjects { get; } // public IList<Dog>? NullableListOfObjects { get; } // Compile-time error // public IList<Dog?> ListOfNullableObjects { get; } // Compile-time error public ISet<Dog> SetOfNonNullableObjects { get; } // public ISet<Dog>? NullableSetOfObjects { get; } // Compile-time error // public ISet<Dog?> SetOfNullableObjects { get; } // Compile-time error public IDictionary<string, Dog?> DictionaryOfNullableObjects { get; } // public IDictionary<string, Dog> DictionaryOfNonNullableObjects { get; } // Compile-time error // public IDictionary<string, Dog>? NullableDictionaryOfObjects { get; } // Compile-time error [] public IQueryable<Dog> MyDogs { get; } // [Backlink(nameof(Dog.People))] // public IQueryable<Dog?> MyDogs { get; } // Compile-time error }
Nota
Si utilizas la definición anterior de tipo de esquema (tus clases derivan de la clase base RealmObject), o no tienes habilitada la nulabilidad, necesitarás usar el [Obligatorio] atributo para cualquier propiedad string y byte[] obligatoria.
Ignoring Nullability
Puedes preferir tener mayor flexibilidad al definir la anulabilidad de las propiedades en los objetos de Realm. Puedes hacerlo configurando realm.ignore_objects_nullability = true en un archivo de configuración global.
If you enable realm.ignore_objects_nullability, nullability annotations will be ignored on Realm object properties, including collections of Realm objects.