Docs Menu

Docs HomeRealm

Quick Start - .NET SDK

On this page

  • Import Realm
  • Define Your Object Model
  • Open a Local Realm
  • Create, Read, Update, and Delete Objects
  • Watch for Changes
  • Add Device Sync (Optional)
  • Prerequisites
  • Initialize the App
  • Use Object Models with Sync
  • Authenticate a User
  • Open a Synced Realm

This Quick Start demonstrates how to use Realm Database with the Realm .NET SDK. Before you begin, ensure you have Installed the .NET SDK.

In the shared code project of your solution, go to Manage NuGet Packages. In the NuGet Package Manager, switch to the Browse tab and then search for Realm. Select the latest version of the Realm package, and then click Add Package.

Adding Realm via Nuget

At the top of each C# file that uses Realm, add the following using statement:

using Realms;

Your application's object model defines the data that you can store within Realm Database and synchronize to and from App Services.

Important

Inheritance

All Realm objects must derive from RealmObject, EmbeddedObject, or AsymmetricObject.

The following code shows how to define an object model for a Task object. In this example, we have marked the Id field as the Primary Key, marked the Name and Status properties as "required", and are using the MapTo attribute so we can use .NET-friendly casing on our property names.

using MongoDB.Bson;
using Realms;
namespace Examples.Models
{
public class Task : RealmObject
{
[PrimaryKey]
[MapTo("_id")]
public ObjectId Id { get; set; } = ObjectId.GenerateNewId();
[MapTo("_partition")]
[Required]
public string Partition { get; set; }
[MapTo("assignee")]
public User Assignee { get; set; }
[MapTo("name")]
[Required]
public string Name { get; set; }
[MapTo("status")]
[Required]
public string Status { get; set; }
}
public enum TaskStatus
{
Open,
InProgress,
Complete
}
}

In a local-only Realm Database, you open a realm with either the Realm.GetInstance() or Realm.GetInstanceAsync() method. Which method you use depends entirely on if and how you are using asynchronous patterns in your app. The following code shows how to use GetInstance():

var realm = Realm.GetInstance();

For more information, see: Open a Realm.

Once you have opened a realm, you can create objects in it. All writes must occur within a Write transaction block.

The following code shows how to create a new Guitar object. In it, we instantiate the Guitar class and then add the new guitar to the realm within a Write() block:

realm.Write(() =>
{
realm.Add(new Guitar()
{
Make = "Gibson",
Model = "Les Paul Custom",
Price = 649.99,
Owner = "N. Young"
});
});

You can retrieve a live collection of all Guitar objects in the realm:

var allGuitars = realm.All<Guitar>();

You can filter the collection by using the Linq syntax:

var lessExpensiveGuitars = realm.All<Guitar>().Where(g => g.Price < 400);
var guitarsSortedByMake = realm.All<Guitar>().OrderBy(g => g.Make);
var specifiGuitarById = realm.Find<Guitar>(someGuitarId);

To modify a realm object, update its properties in a write transaction block:

var davidsStrat = realm.All<Guitar>().FirstOrDefault(
g => g.Owner == "D. Gilmour"
&& g.Make == "Fender"
&& g.Model == "Stratocaster");
realm.Write(() =>
{
davidsStrat.Price = 1700345.56;
});

Finally, you can delete a todo:

var mostExpensiveGuitar = realm.All<Guitar>()
.OrderByDescending(g => g.Price).First();
realm.Write(() =>
{
realm.Remove(mostExpensiveGuitar);
});

You can watch a realm, collection, or object for changes with the SubscribeForNotifications() method.

Important

Serverless Limitations

You cannot watch for changes if the data source is an Atlas serverless instance. MongoDB serverless currently does not support change streams, which are used on watched collections to listen for changes.

Be sure to retain the notification token returned by SubscribeForNotifications as long as you want to continue watching for changes. When you are done, call the Dispose() method:

var token = fido.Owners.SubscribeForNotifications((sender, changes, error) =>
{
if (error != null) return;
if (changes == null) return;
});
token.Dispose();

If you want to sync Realm data across devices, you can set up an Atlas App Services App and enable Device Sync. For more information on what you can do with App Services, see: Application Services - .NET SDK.

Before you can sync Realm data, you must:

In the following code, we have enabled anonymous authentication and are using the ownerId as the unique field in the Flexible Sync configuration.

To use App Services features such as authentication and sync, access your App Services App using your App ID. You can find your App ID in the App Services UI.

You then initialize your app:

app = App.Create(myRealmAppId);

When using Sync, you can define your object models directly in code only if you enabled Sync with Development Mode in the App Services UI.

Note

Get Schema from UI if Development Mode Disabled

If you have enabled Sync but turned off Development Mode, you can copy and paste the object model definitions that App Services generated for you from the SDKs tab in the App Services UI. You must re-enable Development Mode if you want to make changes to the object model definition from client side code.

For more information, see Create a Data Model.

In this quick start, we are using anonymous authentication to log in users without requiring them to provide any identifying information. After authenticating the user, you can open a realm for that user.

var user = await app.LogInAsync(Credentials.Anonymous());

You should also provide a way for the user to log out. The following code shows how to do this by calling LogOutAsync():

await user.LogOutAsync();

The Realm .NET SDK provides many additional ways to authenticate, register, and link users. For other authentication providers, see: Authenticate Users - .NET SDK

Once you have enabled Device Sync and authenticated a user, you can open a synced realm. Use a FlexibleSyncConfiguration object to control the specifics of how your application synchronizes data with App Services. You then add a Flexible Sync subscription that determines what data the user can query.

var config = new FlexibleSyncConfiguration(app.CurrentUser)
{
PopulateInitialSubscriptions = (realm) =>
{
var myTasks = realm.All<Task>().Where(n => n.OwnerId == myUserId);
realm.Subscriptions.Add(myTasks);
}
};
// The process will complete when all the user's tasks have been downloaded.
var realm = await Realm.GetInstanceAsync(config);

The syntax to read, write, and watch for notifications on a synced realm is identical to the syntax for non-synced realms above. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.

←  Install Realm - .NET SDKWork with Realm Files - .NET SDK →
Share Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.