Docs Menu

Object Models & Schemas - .NET SDK

On this page

  • Example
  • Object Schema
  • Embedded Objects
  • Attributes
  • Primary Key
  • Indexes
  • Data Binding and MVVM
  • Summary

MongoDB Realm applications model data as objects composed of property-value pairs that each contain one or more primitive data types or other Realm objects. Realm objects are essentially the same as regular objects, but they inherit from RealmObject or EmbeddedObject and include additional features like real-time updating data views and reactive change event handlers.

Every Realm object has an object type that refers to the object's class. Objects of the same type share an object schema that defines the properties and relationships of those objects.

In C#, you typically define object schemas by using the C# class declarations. When Realm is initialized, it discovers the Realm objects defined in all assemblies that have been loaded and generates schemas accordingly. This is the simplest approach to defining a schema, and is generally the least error-prone. However, this approach includes all loaded Realm objects, and there may be cases where you only want to use a subset of classes, or to customize Realm object schemas. To do this, you can programmatically define a schema.

Note

.NET does not load an assembly until you reference a class in it, so if you define your object models in one assembly and instantiate Realm in another, be sure to call a method in the assembly that contains the object models before initialization. Otherwise, Realm will not discover the objects when it first loads.

Example

The following code block shows an object schema that describes a Dog. Every Dog object must include a Name and may optionally include the dog's Age, Breed and a list of people that represents the dog's Owners.

public class Dog : RealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
[Required]
public string Name { get; set; }
public int Age { get; set; }
public string Breed { get; set; }
public IList<Person> Owners { get; }
}
public class Person : RealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; }
[Required]
public string Name { get; set; }
//etc...
/* To add items to the IList<T>:
var dog = new Dog();
var caleb = new Person { Name = "Caleb" };
dog.Owners.Add(caleb);
*/
}
Note

To define a collection of objects within an object, use an 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.

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 Realm Object Model.

Object schemas specify constraints on object properties such as the data type of each property and whether or not a property is required. Schemas can also define relationships between object types in a realm.

Every Realm app has a Realm Schema composed of a list of object schemas for each type of object that the realms in that application may contain. MongoDB Realm guarantees that all objects in a realm conform to the schema for their object type and validates objects whenever they're created, modified, or deleted.

Realm Database provides the ability to nest objects within other objects. This has several advantages:

  • If using Realm Sync, objects will translate into MongoDB documents that follow a denormalized data model.
  • When you delete an object that contains another object, the delete operation removes both objects from the realm, so unused objects don't accumulate in your realm file, taking up valuable space on user's mobile devices.
Tip
See also:

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

  • ObjectId
  • string
  • char
  • byte
  • short
  • int
  • long

You may define a primary key on a single property for an object type as part of the object schema. Realm Database 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.

Indexes support the efficient execution of queries in Realm Database. Without indexes, Realm Database must perform a collection scan, i.e. scan every document in a collection, to select those documents that match a query. If an appropriate index exists for a query, Realm Database can use the index to limit the number of documents that it must inspect.

Indexes are special data structures that store a small portion of a realm's data in an easy to traverse form. The index stores the value of a specific property ordered by the value of the property. The ordering of the index entries supports efficient equality matches and range-based query operations.

Adding an index to a property makes write operations slightly slower, but makes certain queries faster. Indexes require space in your realm file, so adding an index to a property will increase disk space consumed by your realm file.

You can index properties with the following types:

  • bool
  • byte
  • short
  • int
  • long
  • DateTimeOffset
  • char
  • string
  • ObjectId

When building a Xamarin app using the MVVM pattern, you often want proper data binding in both directions between the View and ViewModel: if a property value changes in the UI, the ViewModel should be notified, and vice-versa. ViewModels typically implement the INotifyPropertyChange interface to ensure this.

However, when you bind UI elements to a RealmObject, this notification happens automatically, thus greatly simplifying your ViewModel code.

You can also bind a UI element to a realm Live Query. For example, if you bind a ListView to a live query, then the list will update automatically when the results of the query change; you do not need to implement the INotifyPropertyChange interface.

For example, if you bind a ListView to a query that returns all Product objects, the list of available products updates automatically when a product is added, changed, or removed from the realm:

// Somewhere in your ViewModel
AllProducts = realm.All<Products>();
<!-- Somewhere in your View -->
<ListView ItemsSource="{Binding AllProducts}">
  • Realm objects are of a type defined as you would any other class.
  • Realm objects are live: they always reflect the latest version on disk and update automatically when the underlying object changes.
  • A Realm object type may have a primary key property to uniquely identify each instance of the object type.
  • The Realm object's schema defines the properties of the object and which properties are optional, which properties have a default value, and which properties are indexed.
  • Using realm objects and queries in a MVVM architecture simplifies data binding.
Give Feedback
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.