Navigation

Embedded Objects

Overview

An embedded object is a special type of Realm object that models complex data about a specific object. Embedded objects are similar to relationships, but they provide additional constraints and map more naturally to the denormalized MongoDB document model.

Realm enforces unique ownership constraints that treat each embedded object as nested data inside of a single, specific parent object. An embedded object inherits the lifecycle of its parent object and cannot exist as an independent Realm object. Realm automatically deletes embedded objects if their parent object is deleted or when overwritten by a new embedded object instance.

Realm Uses Cascading Deletes for Embedded Objects

When you delete a Realm object, Realm automatically deletes any embedded objects referenced by that object. Any objects that your application must persist after the deletion of their parent object should use relationships instead.

Embedded Object Data Models

You can define embedded object types using either Realm object models or a server-side document schema. Embedded object types are reusable and composable . You can use the same embedded object type in multiple parent object types and you can embed objects inside of other embedded objects.

Important

Embedded objects cannot have a primary key.

Realm Object Models

To specify that a Realm object model defines an embedded object, derive the embedded object class from EmbeddedObject. Use the syntax - “<YourClass> : EmbeddedObject {}” to accomplish this. You can reference an embedded object type from parent object types in the same way as you would define a relationship.

Consider the following example where the Address is an Embedded Object. Both the Contact and the Business classes reference the Address as an embedded object:

public class Address : EmbeddedObject
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }

}
public class Contact : RealmObject
{

    [PrimaryKey]
    [MapTo("_id")]
    public ObjectId Id { get; set; } = ObjectId.GenerateNewId();

    public string Name { get; set; }

    public Address Address { get; set; } // embed a single address 

}
public class Business : RealmObject
{
    [PrimaryKey]
    [MapTo("_id")]
    public ObjectId Id { get; set; } = ObjectId.GenerateNewId();

    public string Name { get; set; }
    public IList<Address> addresses { get; }
}

JSON Schema

Unlike regular Realm objects, which map to their own MongoDB collection, embedded objects map to embedded documents in the parent type’s document schema:

{
  "title": "Contact",
  "bsonType": "object",
  "required": ["_id", "name", "address"],
  "properties": {
    "_id": "objectId",
    "name": "string",
    "address": {
      "title": "Address",
      "bsonType": "object",
      "properties": {
        "street": "string",
        "city": "string",
        "country": "string",
        "postalCode": "string"
      }
    }
  }
}
{
  "title": "Business",
  "bsonType": "object",
  "required": ["_id", "name", "addresses"],
  "properties": {
    "_id": "objectId",
    "name": "string",
    "addresses": {
      "bsonType": "array",
      "items": {
        "title": "Address",
        "bsonType": "object",
        "properties": {
          "street": "string",
          "city": "string",
          "country": "string",
          "postalCode": "string"
        }
      }
    }
  }
}

Read and Write Embedded Objects

Create an Embedded Object

To create an embedded object, assign an instance of the embedded object to a parent object’s property:

Address address = new Address() // Create an Address
{
    Street = "123 Fake St.",
    City = "Springfield",
    Country = "USA",
    PostalCode = "90710"
};

Contact contact = new Contact() // Create a Contact
{
    Name = "Nick Riviera",
    Address = address // Embed the Address Object
};

realm.Write(() =>
{
    realm.Add(contact);
});

Update an Embedded Object Property

To update a property in an embedded object, modify the property in a write transaction:

var resultContact = realm.All<Contact>() // Find the First Contact (Sorted By Name)
    .OrderBy(c => c.Name)
    .FirstOrDefault();

// Update the Result Contact's Embedded Address Object's Properties
realm.Write(() =>
{
    resultContact.Address.Street = "Hollywood Upstairs Medical College";
    resultContact.Address.City = "Los Angeles";
    resultContact.Address.PostalCode = "90210";
});

Overwrite an Embedded Object

To overwrite an embedded object, reassign the embedded object property of a party to a new instance in a write transaction:

Contact oldContact = realm.All<Contact>() // Find the first contact
    .OrderBy(c => c.Name)
    .FirstOrDefault();


Address newAddress = new Address() // Create an Address
{
    Street = "100 Main Street",
    City = "Los Angeles",
    Country = "USA",
    PostalCode = "90210"
};

realm.Write(() =>
{
    oldContact.Address = newAddress;
});

Query a Collection on Embedded Object Properties

Use dot notation to filter or sort a collection of objects based on an embedded object property value:

Note

It is not possible to query embedded objects directly. Instead, access embedded objects through a query for the parent object type.

var losAngelesContacts = realm.All<Contact>().Filter("Address.City == 'Los Angeles'"); // Find All Contacts with an Address of "Los Angeles"

foreach (Contact losAngelesContact in losAngelesContacts)
{
    Console.WriteLine("Los Angeles Contact:");
    Console.WriteLine(losAngelesContact.Name);
    Console.WriteLine(losAngelesContact.Address.Street);
}