Here is a simple example on how to use MongoDB Realm with C#.
What is MongoDB Realm?
MongoDB Realm will combine Realm, the popular mobile database and data synchronization technology, and MongoDB Stitch, the serverless platform for MongoDB, into a unified solution that makes it easy for you to build powerful and engaging experiences on more devices. See realm.io
So basically, it’s a offline first database framework that helps you to manage the two ways synchronization issue. Really useful for mobile apps.
How to use MongoDB Realm?
- Download the Realm NuGet Package
- Configure your Realm DB with RealmConfiguration
- Get an instance of Realm with Realm.GetInstance()
- Insert your objects into the DB with realm.Add() and realm.Write()
- Retreive your object with realm.All() or realm.Find()
How to use MongoDB Realm with C#?
Follow this simple tutorial to understand the basics of Realm with C#:
using Realms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Realm_Demo
{
class Program
{
static async Task Main(string[] args)
{
Realm realm = null;
RealmConfiguration config = null;
try
{
//If you don't want to store in a file
//config = new InMemoryConfiguration("some-identifier");
//Set the path of your db file
var dbName = "MyRealmDb.realm";
config = new RealmConfiguration(dbName);
//Get the Realm instance
realm = await Realm.GetInstanceAsync(config);
//Get the db path
string dbFullPath = realm.Config.DatabasePath;
//Create a new Employee and link it to a new Company
var employee1Name = "Elon Musk";
var employee1 = new Employee { Name = employee1Name, Salary = 5000 };
var company1 = new Company { Name = "SpaceX" };
company1.Employees.Add(employee1); //There is no setter in the IList!
//Let's create an other employee containing a mistake that we will fix later on
var employee2 = new Employee { Name = "Jeff Beeezo", Salary = 7000 };
var company2 = new Company { Name = "Blue Origin" };
company2.Employees.Add(employee2);
//THIS IS HOW TO WRITE IN REALM DB IN 3 DIFFERENT WAYS:
// 1) Update and persist objects with a thread-safe transaction
await realm.WriteAsync((tmpRealm) =>
{
tmpRealm.RemoveAll(); //Clean the db
tmpRealm.Add(company1);
tmpRealm.Add(company2);
});
// 2) Using Realm commit in a transaction that can rollback the changes
using (Transaction transaction = realm.BeginWrite())
{
employee2.Name = "Jeff Bezo"; //update the name of our employee
transaction.Commit();
}
// 3) Query and update from any thread
var myTask = new Thread(() =>
{
var realm2 = Realm.GetInstance(config);
var theBoss = realm2.All<Employee>().Where(x => x.Name == employee1Name).First();
realm2.Write(() => theBoss.Salary = 10000);
});
myTask.Start();
myTask.Join();
//Refresh the Realm instance
realm.Refresh();
//Display what we have in the DB now:
foreach (var company in realm.All<Company>())
{
Console.WriteLine($"Company Name: {company.Name}");
foreach (var employee in company.Employees)
Console.WriteLine($"\tEmployee Name: {employee.Name}\r\n\tSalary: {employee.Salary}");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
//Cleaning
realm.Dispose();
//Realm.DeleteRealm(config); //Delete the db
}
Console.WriteLine("\r\nPress any key...");
Console.ReadKey();
}
}
public class Employee : RealmObject
{
public string Name { get; set; }
public int Salary { get; set; }
}
public class Company : RealmObject
{
public string Name { get; set; }
public IList<Employee> Employees { get; }
}
}
Code language: C# (cs)
Happy coding! 🙂