Quick Start - .NET SDK
On this page
- Install Realm
- Open the NuGet Package Manager
- Add the Realm Package
- Open the NuGet Package Manager
- Add the Realm Package
- Add the Realm Weaver to FodyWeavers.xml
- 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. It then demonstrates adding Device Sync with Atlas App Services to your app. Before you begin, ensure you have Installed the .NET SDK.
Install Realm
Follow these steps to add the Realm .NET SDK to your project.
Important
Install the SDK for all projects
If you have a multi-platform solution, be sure to install the SDK for all of the platform projects, even if the given project doesn't contain any Realm-specific code.
Import Realm
Add the following line to the top of your source files to use Realm:
using Realms;
Define Your Object Model
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 inherit from the
IRealmObject,
IEmbeddedObject, or
IAsymmetricObject
interface and should be declared partial
classes.
You can also derive from the RealmObject, EmbeddedObject, or AsymmetricObject base classes. However, in the future we may deprecate the base classes. You should use the interfaces for any new classes that you write.
The following code shows how to define an object model for a Item
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 when using
Device Sync.
using MongoDB.Bson; using Realms; namespace Examples.Models { public class Item : RealmObject { [ ] [ ] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); [ ] [ ] public string Partition { get; set; } [ ] public User Assignee { get; set; } [ ] [ ] public string Name { get; set; } [ ] [ ] public string Status { get; set; } }
Open a Local Realm
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.
Create, Read, Update, and Delete Objects
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); });
Watch for Changes
You can watch a realm, collection, or object for changes with the SubscribeForNotifications() method.
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();
Add Device Sync (Optional)
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.
Prerequisites
Before you can sync Realm data, you must:
Enable and configure one or more authentication providers
Enable Flexible Sync with Development Mode toggled to
On
and an unique field in the Queryable Fields section.
In the following code, we have enabled anonymous authentication and are using
the ownerId
as the unique field in the Flexible Sync configuration.
Initialize the App
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);
Use Object Models with Sync
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.
Authenticate a User
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
Open a Synced Realm
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 myItems = realm.All<Item>().Where(n => n.OwnerId == myUserId); realm.Subscriptions.Add(myItems); } }; // The process will complete when all the user's items 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.