Realm permite definir relaciones explícitas entre los tipos de objetos de una aplicación. Una relación es una propiedad de un objeto que hace referencia a otro objeto de Realm, en lugar de a uno de los tipos de datos primitivos. Las relaciones se definen asignando el tipo de propiedad a otra clase de Realm.
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 a 10.18.0, los objetos derivan de las clases base RealmObject, EmbeddedObject o AsymmetricObject. Este enfoque para definir el modelo de Realm aún se admite, pero no incluye nuevas funcionalidades como las anotaciones de nulabilidad. En una versión futura del SDK, las clases base quedarán obsoletas. Se debe usar las interfaces para cualquier clase nueva que escribas y considerar migrar tus clases existentes.
Relationships are direct references to other objects in a realm, which means that you don't need bridge tables or explicit joins to define a relationship like you would in a relational database. Instead, you can access related objects by reading and writing to the property that defines the relationship. Realm executes read operations lazily as they come in, so querying a relationship is just as performant as reading a regular property.
Definir una propiedad de relación
Tip
Alternatively, you can define your relationships in your App Services app.
Hay tres tipos principales de relaciones entre objetos:
To-One Relationship
A to-one relationship means that an object is related in a specific way to no more than one other object. You define a to-one relationship for an object type in its object schema by specifying a property where the type is the related Realm object type.
Ejemplo
An application could use the following object schemas to indicate that a Person may or may not own a single Dog by including it in its dog property:
public partial class Person : IRealmObject { [] [] public ObjectId Id { get; set; } public string Name { get; set; } public DateTimeOffset Birthdate { get; set; } public Dog? Dog { get; set; } } public partial class Dog : IRealmObject { [] [] public ObjectId Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Breed { get; set; } = String.Empty; }
To query a direct relationship, you can use LINQ syntax. See the following example for how to query a one-to-one relationship:
var fidosPerson = realm.All<Person>().FirstOrDefault(p => p.Dog == dog);
Relación de muchos
A to-many relationship means that an object is related in a specific way to multiple objects. You define a to-many relationship for an object type by specifying a property where the type is an IList<T> of the related Realm object type. Define the IList<T> with only a getter. You do not need to initialize it in the constructor, as Realm will generate a collection instance the first time the property is accessed:
// To add items to the IList<T>: var person = new Person(); person.Dogs.Add(new Dog { Name = "Caleb", Age = 7, Breed = "mutt" });
Ejemplo
An application could use the following object schemas to indicate that a Person may own multiple Dogs by including them in its dog property:
public partial class Person : IRealmObject { [] [] public ObjectId Id { get; set; } public string Name { get; set; } public DateTimeOffset Birthdate { get; set; } public IList<Dog> Dogs { get; } } public partial class Dog : IRealmObject { [] [] public ObjectId Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Breed { get; set; } = String.Empty; }
To see the to-many relationship of Person to Dog, you query for the Person and get that person's Dogs:
var katieAndHerDogs = realm.All<Person>(). Where(p => p.Name == "Katie") .FirstOrDefault();
Relación inversa
An inverse relationship links an object back to any other objects that refer to it in a defined to-one or to-many relationship. Relationship definitions are unidirectional, so you must explicitly define a property in the object's model as an inverse relationship.
Por ejemplo, la relación de uno a muchos "un Usuario tiene muchos Elementos" no crea automáticamente la relación inversa "un Elemento pertenece a un Usuario". Si no especificas la relación inversa en el Modelo de objeto, necesitas ejecutar una separate query para buscar al usuario que está asignado a un elemento determinado.
Para definir la relación inversa, defina una IQueryable<T> propiedad solo para captadores en su modelo de objetos, donde T es el tipo de origen de la relación, y luego anote esta propiedad con un atributo [Backlink(sourceProperty)], donde "sourceProperty" es el nombre de la propiedad en el otro lado de la relación. El siguiente ejemplo muestra cómo hacerlo en el escenario "El usuario tiene muchos elementos":
public partial class User : IRealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); public string Name { get; set; } [] public IQueryable<Item> Items { get; } } public partial class Item : IRealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); public string Text { get; set; } public User? Assignee { get; set; } }
In this example, note that:
The Item object's
Assigneeproperty is a User object.La propiedad
Itemsdel objeto Usuario invierte la relación y hace referencia a todos los objetos Elemento que contienen este Usuario específico en su propiedadAssignee.
This, then, allows us to query the Item collection to get all Items assigned to a specific User.
To query the inverse relationship, you cannot use Linq. Instead, pass a string predicate. The following example shows how you could find all Users who have Items that contain the word "oscillator":
var oscillatorAssignees = realm.All<User>() .Filter("Items.Text CONTAINS 'oscillator'").ToList(); foreach (User u in oscillatorAssignees) { Console.WriteLine(u.Name); }
Resumen
A relationship is an object property that allows an object to reference other objects of the same or another object type.
Relationships are direct references. You can access related objects directly through a relationship property without writing any type of join.
Realm admite relaciones de uno a muchos e inversas.