Navigation

Read & Write Data - .NET SDK

A read from a realm generally consists of the following steps:

Note
About the examples on this page

The examples on this page use the data model of a project management app that has two Realm object types: Project and Task. A Project has zero or more Tasks.

See the schema for these two classes, Project and Task, below:

public class Task : RealmObject
{
[PrimaryKey]
public int Id {get; set; }
public string Name { get; set; }
public string Assignee { get; set; }
public bool IsComplete { get; set; }
public int Priority { get; set; }
public int ProgressMinutes { get; set; }
}
public class Project : RealmObject
{
public string Name { get; set; }
public List<Task> Tasks { get; set; }
}

You can also find a specific item by its primary key using the Find method, as shown in the following example:

// Object to be stored in the Realm instance
var myTask = new Task
{
Id = 1
};
realm.Write(() =>
{
realm.Add(myTask);
});
// Other code...
// Find specific object by primary key
var obj = realm.Find<Task>(1);

The first step of any read is to get all objects of a certain type in a realm. With this results collection, you can operate on all instances on a type or filter and sort to refine the results.

Example

In order to access all instances of Project and Task, use the following syntax:

var projects = realm.All<Project>();
var tasks = realm.All<Task>();

A filter selects a subset of results based on the value(s) of one or more object properties. Realm Database provides a full-featured query engine you can use to define filters. The most common use case is to find objects where a certain property matches a certain value. Additionally, you can compare strings, aggregate over collections of numbers, and use logical operators to build up complex queries.

Example

In the following example, we use the query engine's comparison operators to:

  • Find high priority tasks by comparing the value of the priority property value with a threshold number, above which priority can be considered high.
  • Find just-started or short-running tasks by seeing if the progressMinutes property falls within a certain range.
  • Find unassigned tasks by finding tasks where the assignee property is equal to null.
  • Find tasks assigned to specific teammates Ali or Jamie by seeing if the assignee property is in a list of names.
Debug.WriteLine("High priority tasks: "
+ tasks.Where(t => t.Priority > 5));
Debug.WriteLine("Just started or short tasks: "
+ tasks.Where(t => 1 <= t.ProgressMinutes && t.ProgressMinutes < 15));
Debug.WriteLine("Unassigned tasks: "
+ tasks.Where(t => t.Assignee == null));
Debug.WriteLine("Ali or Jamie's tasks: "
+ tasks.Where(t => new List<string> { "Ali", "Jamie" }.Contains(t.Assignee)));

A sort operation allows you to configure the order in which Realm Database returns queried objects. You can sort based on one or more properties of the objects in the results collection.

Realm Database only guarantees a consistent order of results when the results are sorted.

Example

The following code sorts the projects by name in reverse alphabetical order (i.e. "descending" order).

var projectsSorted = projects.OrderByDescending(p => p.Name);

When writing (creating and updating) documents, all writes must happen in a transaction.

Example

The following code shows how to run a transaction with the realm's write method. If the code in the callback throws an exception, Realm Database cancels the transaction. Otherwise, Realm Database commits the transaction.

realm.Write(() =>
{
// Create someone to take care of ssome dogs.
var ali = new Person { Id = 1, Name = "Ali" };
realm.Add(ali);
// Find dogs younger than 2.
var puppies = realm.All<Dog>().Where(dog => dog.Age < 2);
// Loop through one by one to update.
foreach (var puppy in puppies)
{
// Give all the puppies to Ali.
puppy.Owner = ali;
}
});
Example

This code demonstrates how to create an object with Realm Database:

// Open a thread-safe transaction.
realm.Write(() =>
{
// Instantiate a class, as normal.
var dog = new Dog { Name = "Max", Age = 5 };
// Add the instance to the realm.
realm.Add(dog);
});
Example

This code changes the dog's name to "Wolfie" and increments the age by 1:

// Open a thread-safe transaction.
realm.Write(() =>
{
// Get a dog to update.
var dog = realm.All<Dog>().First();
// Update some properties on the instance.
// These changes are saved to the realm.
dog.Name = "Wolfie";
dog.Age += 1;
});
Example

This code demonstrates how to upsert an object with realm. We create a new user named "Drew" and then update their name to "Andy" via upsert:

realm.Write(() =>
{
var drew = new Person { Id = 1234, Name = "Drew" };
// Add a new person to the realm. Since nobody with ID 1234
// has been added yet, this adds the instance to the realm.
realm.Add(drew, update: true);
var andy = new Person { Id = 1234, Name = "Andy" };
// Judging by the ID, it's the same person, just with a different name.
// When `update` is true, you overwrite the original entry (i.e. Drew -> Andy).
realm.Add(andy, update: true);
});
Example

The following code demonstrates how to update a collection. Thanks to the implicit inverse relationship between the Dog's owner property and the Person's dogs property, Realm Database automatically updates Ali's list of dogs.

realm.Write(() =>
{
// Create someone to take care of ssome dogs.
var ali = new Person { Id = 1, Name = "Ali" };
realm.Add(ali);
// Find dogs younger than 2.
var puppies = realm.All<Dog>().Where(dog => dog.Age < 2);
// Loop through one by one to update.
foreach (var puppy in puppies)
{
// Give all the puppies to Ali.
puppy.Owner = ali;
}
});
Example

The following code shows how to delete one object from its realm:

realm.Write(() =>
{
// Remove the instance from the realm.
realm.Remove(dog);
// Discard the reference.
dog = null;
});
Example

The following code demonstrates how to delete a collection from a realm:

realm.Write(() =>
{
// Find dogs younger than 2 years old.
var puppies = realm.All<Dog>().Where(dog => dog.Age < 2);
// Remove the collection from the realm.
realm.RemoveRange(puppies);
});

Sometimes, you have dependent objects that you want to delete when you delete the parent object. We call this a cascading delete. Realm Database will not delete the dependent objects for you. If you do not delete the objects yourself, they will remain orphaned in your realm. Whether or not this is a problem depends on your application's needs.

Currently, the best way to delete dependent objects is to iterate through the dependencies and delete them before deleting the parent object.

Example

The following code demonstrates how to perform a cascading delete by first deleting all of Ali's dogs, then deleting Ali:

realm.Write(() =>
{
// Remove all of Ali's dogs.
realm.RemoveRange(ali.Dogs);
// Remove Ali.
realm.Remove(ali);
});

Realm Database supports deleting all instances of a Realm type from a realm.

Example

The following code demonstrates how to delete all Dog instances from a realm:

realm.Write(() =>
{
// Remove all instances of Dog from the realm.
realm.RemoveAll<Dog>();
});

It is possible to delete all objects from the realm. This does not affect the schema of the realm. This is useful for quickly clearing out your realm while prototyping.

Example

The following code demonstrates how to delete everything from a realm:

realm.Write(() =>
{
// Remove all objects from the realm.
realm.RemoveAll();
});
Give Feedback