Class Realm
A Realm instance (also referred to as a Realm) represents a Realm database.
Warning: Non-frozen Realm instances are not thread safe and can not be shared across threads.
You must call GetInstance(RealmConfigurationBase?) on each thread in which you want to interact with the Realm.
Implements
Namespace: Realms
Assembly: Realm.dll
Syntax
public class Realm : IDisposable
Properties
| Edit this page View SourceConfig
Gets the RealmConfigurationBase that controls this realm's path and other settings.
Declaration
public RealmConfigurationBase Config { get; }
Property Value
Type | Description |
---|---|
RealmConfigurationBase | The Realm's configuration. |
DynamicApi
Gets an object encompassing the dynamic API for this Realm instance.
Declaration
[Preserve]
public Realm.Dynamic DynamicApi { get; }
Property Value
Type | Description |
---|---|
Realm.Dynamic | A Realm.Dynamic instance that wraps this Realm. |
IsClosed
Gets a value indicating whether the instance has been closed via Dispose(). If true
, you
should not call methods on that instance.
Declaration
public bool IsClosed { get; }
Property Value
Type | Description |
---|---|
bool |
|
IsFrozen
Gets a value indicating whether this Realm is frozen. Frozen Realms are immutable and will not update when writes are made to the database. Unlike live Realms, frozen Realms can be used across threads.
Declaration
public bool IsFrozen { get; }
Property Value
Type | Description |
---|---|
bool |
|
IsInTransaction
Gets a value indicating whether there is an active write transaction associated with this Realm.
Declaration
public bool IsInTransaction { get; }
Property Value
Type | Description |
---|---|
bool |
|
See Also
| Edit this page View SourceSchema
Gets the RealmSchema instance that describes all the types that can be stored in this Realm.
Declaration
public RealmSchema Schema { get; }
Property Value
Type | Description |
---|---|
RealmSchema | The Schema of the Realm. |
UseLegacyGuidRepresentation
Gets or sets a value indicating whether to use the legacy representation when storing Guid values in the database.
Declaration
[Obsolete("It is strongly advised to migrate to the new Guid representation as soon as possible to avoid data inconsistency.")]
public static bool UseLegacyGuidRepresentation { get; set; }
Property Value
Type | Description |
---|---|
bool |
Remarks
In versions prior to 10.10.0, the .NET SDK had a bug where it would store Guid values with architecture-specific byte ordering
(little-endian for most modern CPUs) while the database query engine and Sync would always treat them as big-endian. This manifests
as different string representations between the SDK and the database - e.g. "f2952191-a847-41c3-8362-497f92cb7d24" instead of
"912195f2-47a8-c341-8362-497f92cb7d24" (notice the swapped bytes in the first 3 components). Starting with 10.10.0, big-endian
representation is the default one and a seamless one-time migration is provided for local (non-sync) Realms. The first time a
Realm is opened, all properties holding a Guid value will be updated from little-endian to big-endian format and the .NET SDK
will treat them as such. There should be no noticeable change when reading/writing data from the SDK, but you should see consistent
values when accessing the Realm file from Realm Studio or other SDKs.
For synchronized Realms, such a migration is impossible due to the distributed nature of the data. Therefore, the assumption
is that the Guid representation in Atlas if authoritative and the SDK values should be updated to match it. THIS MEANS THAT THE
SDK WILL START REPORTING A DIFFERENT STRING REPRESENTATION OF EXISTING GUID DATA COMPARED TO pre-10.10.0. If you are querying
3rd party systems from the SDK, you might see unexpected results. To preserve the existing behavior (little-endian in the SDK,
big-endian in Atlas), set this value to true
and reach out to the Realm support team (https://support.mongodb.com) for
help with migrating your data to the new format.
Methods
| Edit this page View SourceAdd<T>(IEnumerable<T>, bool)
Add a collection of standalone RealmObjects to this Realm.
Declaration
public void Add<T>(IEnumerable<T> objs, bool update = false) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
IEnumerable<T> | objs | A collection of IRealmObject instances that will be added to this Realm. |
bool | update | If |
Type Parameters
Name | Description |
---|---|
T | The Type T must not only be a IRealmObject but also have been processed by the Fody weaver, so it has persistent properties. |
Remarks
If the collection contains items that are already managed by this Realm, they will be ignored.
This method modifies the objects in-place, meaning that after it has run, all items in objs
will be managed.
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
RealmObjectManagedByAnotherRealmException | You can't manage an object with more than one Realm. |
Add<T>(T, bool)
This Realm will start managing an IRealmObject which has been created as a standalone object.
Declaration
public T Add<T>(T obj, bool update = false) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
T | obj | Must be a standalone object, |
bool | update | If |
Returns
Type | Description |
---|---|
T | The passed object, so that you can write |
Type Parameters
Name | Description |
---|---|
T | The Type T must not only be a IRealmObject but also have been processed by the Fody weaver, so it has persistent properties. |
Remarks
If the object is already managed by this Realm, this method does nothing.
This method modifies the object in-place, meaning that after it has run, obj
will be managed.
Returning it is just meant as a convenience to enable fluent syntax scenarios.
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
RealmObjectManagedByAnotherRealmException | You can't manage an object with more than one Realm. |
All<T>()
Extract an iterable set of objects for direct use or further query.
Declaration
public IQueryable<T> All<T>() where T : IRealmObject
Returns
Type | Description |
---|---|
IQueryable<T> | A queryable collection that without further filtering, allows iterating all objects of class T, in this Realm. |
Type Parameters
Name | Description |
---|---|
T | The Type T must be an IRealmObject. |
Remarks
The returned collection is evaluated lazily and no objects are being held in memory by the collection itself, which means this call is very cheap even for huge number of items.
BeginWrite()
Begins a write transaction for this Realm.
Declaration
public Transaction BeginWrite()
Returns
Type | Description |
---|---|
Transaction | A transaction in write mode, which is required for any creation or modification of objects persisted in a Realm. |
Examples
using (var trans = realm.BeginWrite())
{
realm.Add(new Dog
{
Name = "Rex"
});
trans.Commit();
}
|
Edit this page
View Source
BeginWriteAsync(CancellationToken)
Asynchronously begins a write transaction for this Realm.
Declaration
public Task<Transaction> BeginWriteAsync(CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
CancellationToken | cancellationToken | Optional cancellation token to stop waiting to start a write transaction. |
Returns
Type | Description |
---|---|
Task<Transaction> | An awaitable Task that returns a transaction in write mode. A transaction is required for any creation, deletion or modification of objects persisted in a Realm. |
Remarks
This method asynchronously acquires the write lock and then dispatches the continuation on the original
thread the Realm was opened on. The transaction can then be committed either asynchronously or
synchronously.
When invoked on a thread without SynchronizationContext (i.e. typically background threads), this method
calls BeginWrite() and executes synchronously.
Examples
using (var trans = await realm.BeginWriteAsync())
{
realm.Add(new Dog
{
Name = "Rex"
});
await trans.CommitAsync();
// or just
// trans.Commit();
}
|
Edit this page
View Source
Compact(RealmConfigurationBase?)
Compacts a Realm file. A Realm file usually contains free/unused space. This method removes this free space and the file size is thereby reduced. Objects within the Realm file are untouched.
Declaration
public static bool Compact(RealmConfigurationBase? config = null)
Parameters
Type | Name | Description |
---|---|---|
RealmConfigurationBase | config | Optional configuration. |
Returns
Type | Description |
---|---|
bool |
|
Remarks
The realm file must not be open on other threads. The file system should have free space for at least a copy of the Realm file. This method must not be called inside a transaction. The Realm file is left untouched if any file operation fails.
DeleteRealm(RealmConfigurationBase)
Deletes all files associated with a given Realm if the Realm exists and is not open.
Declaration
public static void DeleteRealm(RealmConfigurationBase configuration)
Parameters
Type | Name | Description |
---|---|---|
RealmConfigurationBase | configuration | A RealmConfigurationBase which supplies the realm path. |
Remarks
The Realm file must not be open on other threads.
All but the .lock file will be deleted by this.
Exceptions
Type | Condition |
---|---|
RealmInUseException | Thrown if the Realm is still open. |
Dispose()
Disposes the current instance and closes the native Realm if this is the last remaining instance holding a reference to it.
Declaration
public void Dispose()
Find<T>(ObjectId?)
Fast lookup of an object from a class which has a PrimaryKey property.
Declaration
public T? Find<T>(ObjectId? primaryKey) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
ObjectId? | primaryKey | Primary key to be matched exactly, same as an == search. |
Returns
Type | Description |
---|---|
T |
|
Type Parameters
Name | Description |
---|---|
T | The Type T must be a IRealmObject. |
Exceptions
Type | Condition |
---|---|
RealmClassLacksPrimaryKeyException | If the IRealmObject class T lacks PrimaryKeyAttribute. |
Find<T>(Guid?)
Fast lookup of an object from a class which has a PrimaryKey property.
Declaration
public T? Find<T>(Guid? primaryKey) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
Guid? | primaryKey | Primary key to be matched exactly, same as an == search. |
Returns
Type | Description |
---|---|
T |
|
Type Parameters
Name | Description |
---|---|
T | The Type T must be a IRealmObject. |
Exceptions
Type | Condition |
---|---|
RealmClassLacksPrimaryKeyException | If the IRealmObject class T lacks PrimaryKeyAttribute. |
Find<T>(long?)
Fast lookup of an object from a class which has a PrimaryKey property.
Declaration
public T? Find<T>(long? primaryKey) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
long? | primaryKey | Primary key to be matched exactly, same as an == search.
An argument of type |
Returns
Type | Description |
---|---|
T |
|
Type Parameters
Name | Description |
---|---|
T | The Type T must be a IRealmObject. |
Exceptions
Type | Condition |
---|---|
RealmClassLacksPrimaryKeyException | If the IRealmObject class T lacks PrimaryKeyAttribute. |
Find<T>(string?)
Fast lookup of an object from a class which has a PrimaryKey property.
Declaration
public T? Find<T>(string? primaryKey) where T : IRealmObject
Parameters
Type | Name | Description |
---|---|---|
string | primaryKey | Primary key to be matched exactly, same as an == search. |
Returns
Type | Description |
---|---|
T |
|
Type Parameters
Name | Description |
---|---|
T | The Type T must be a IRealmObject. |
Exceptions
Type | Condition |
---|---|
RealmClassLacksPrimaryKeyException | If the IRealmObject class T lacks PrimaryKeyAttribute. |
Freeze()
Returns a frozen (immutable) snapshot of this Realm.
A frozen Realm is an immutable snapshot view of a particular version of a Realm's data. Unlike normal Realm instances, it does not live-update to reflect writes made to the Realm, and can be accessed from any thread. Writing to a frozen Realm is not allowed, and attempting to begin a write transaction will throw an exception. All objects and collections read from a frozen Realm will also be frozen. Note: Keeping a large number of frozen Realms with different versions alive can have a negative impact on the filesize of the underlying database. In order to avoid such a situation it is possible to set MaxNumberOfActiveVersions.Declaration
public Realm Freeze()
Returns
Type | Description |
---|---|
Realm | A frozen Realm instance. |
GetInstance(RealmConfigurationBase?)
Factory for obtaining a Realm instance for this thread.
Declaration
public static Realm GetInstance(RealmConfigurationBase? config = null)
Parameters
Type | Name | Description |
---|---|---|
RealmConfigurationBase | config | Optional configuration. |
Returns
Type | Description |
---|---|
Realm | A Realm instance. |
Exceptions
Type | Condition |
---|---|
RealmFileAccessErrorException | Thrown if the file system returns an error preventing file creation. |
GetInstance(string)
Factory for obtaining a Realm instance for this thread.
Declaration
public static Realm GetInstance(string databasePath)
Parameters
Type | Name | Description |
---|---|---|
string | databasePath | Path to the realm, must be a valid full path for the current platform, relative subdirectory, or just filename. |
Returns
Type | Description |
---|---|
Realm | A Realm instance. |
Remarks
If you specify a relative path, sandboxing by the OS may cause failure if you specify anything other than a subdirectory.
Exceptions
Type | Condition |
---|---|
RealmFileAccessErrorException | Thrown if the file system returns an error preventing file creation. |
GetInstanceAsync(RealmConfigurationBase?, CancellationToken)
Factory for asynchronously obtaining a Realm instance.
Declaration
public static Task<Realm> GetInstanceAsync(RealmConfigurationBase? config = null, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
RealmConfigurationBase | config | A configuration object that describes the realm. |
CancellationToken | cancellationToken | An optional cancellation token that can be used to cancel the work. |
Returns
Type | Description |
---|---|
Task<Realm> | An awaitable Task<TResult> that is completed once the remote realm is fully synchronized or after migrations are executed if it's a local realm. |
Remarks
This method will perform any migrations on a background thread before returning an opened instance to the calling thread.
IsSameInstance(Realm)
Determines whether this instance is the same core instance as the passed in argument.
Declaration
public bool IsSameInstance(Realm other)
Parameters
Type | Name | Description |
---|---|---|
Realm | other | The Realm to compare with the current Realm. |
Returns
Type | Description |
---|---|
bool |
|
Remarks
You can, and should, have multiple instances open on different threads which have the same path and open the same Realm.
Refresh()
Update the Realm instance and outstanding objects to point to the most recent persisted version.
Declaration
public bool Refresh()
Returns
Type | Description |
---|---|
bool | Whether the Realm had any updates. Note that this may return true even if no data has actually changed. |
RefreshAsync()
Asynchronously wait for the Realm instance and outstanding objects to get updated to point to the most recent persisted version.
Declaration
public Task<bool> RefreshAsync()
Returns
Type | Description |
---|---|
Task<bool> | Whether the Realm had any updates. Note that this may return true even if no data has actually changed. |
Remarks
On worker threads (where the SynchronizationContext) is null, this will call the blocking Refresh() method instead. On the main thread (or other threads that have SynchronizationContext), this will wait until the instance automatically updates to resolve the task. Note that you must keep a reference to the Realm until the returned task is resolved.
Remove(IRealmObjectBase)
Removes a persistent object from this Realm, effectively deleting it.
Declaration
public void Remove(IRealmObjectBase obj)
Parameters
Type | Name | Description |
---|---|---|
IRealmObjectBase | obj | Must be an object persisted in this Realm. |
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
ArgumentNullException | If |
ArgumentException | If you pass an unmanaged object. |
RemoveAll()
Remove all objects of all types managed by this Realm.
Declaration
public void RemoveAll()
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
RemoveAll<T>()
Remove all objects of a type from the Realm.
Declaration
public void RemoveAll<T>() where T : IRealmObject
Type Parameters
Name | Description |
---|---|
T | Type of the objects to remove. |
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
ArgumentException | If the type T is not part of the limited set of classes in this Realm's Schema. |
RemoveRange<T>(IQueryable<T>)
Remove objects matching a query from the Realm.
Declaration
public void RemoveRange<T>(IQueryable<T> range) where T : IRealmObjectBase
Parameters
Type | Name | Description |
---|---|---|
IQueryable<T> | range | The query to match for. |
Type Parameters
Name | Description |
---|---|
T | Type of the objects to remove. |
Exceptions
Type | Condition |
---|---|
RealmInvalidTransactionException | If you invoke this when there is no write Transaction active on the Realm. |
ArgumentException | If |
ArgumentNullException | If |
ResolveReference<TValue>(Dictionary<TValue>)
Returns the same collection as the one referenced when the ThreadSafeReference.Dictionary<TValue> was first created, but resolved for the current Realm for this thread.
Declaration
public IDictionary<string, TValue>? ResolveReference<TValue>(ThreadSafeReference.Dictionary<TValue> reference)
Parameters
Type | Name | Description |
---|---|---|
ThreadSafeReference.Dictionary<TValue> | reference | The thread-safe reference to the thread-confined IDictionary<TKey, TValue> to resolve in this Realm. |
Returns
Type | Description |
---|---|
IDictionary<string, TValue> | A thread-confined instance of the original IDictionary<TKey, TValue> resolved for the current thread or |
Type Parameters
Name | Description |
---|---|
TValue | The type of the values contained in the dictionary. |
ResolveReference<T>(List<T>)
Returns the same collection as the one referenced when the ThreadSafeReference.List<T> was first created, but resolved for the current Realm for this thread.
Declaration
public IList<T>? ResolveReference<T>(ThreadSafeReference.List<T> reference)
Parameters
Type | Name | Description |
---|---|---|
ThreadSafeReference.List<T> | reference | The thread-safe reference to the thread-confined IList<T> to resolve in this Realm. |
Returns
Type | Description |
---|---|
IList<T> | A thread-confined instance of the original IList<T> resolved for the current thread or |
Type Parameters
Name | Description |
---|---|
T | The type of the objects, contained in the collection. |
ResolveReference<T>(Object<T>)
Returns the same object as the one referenced when the ThreadSafeReference.Object<T> was first created, but resolved for the current Realm for this thread.
Declaration
public T? ResolveReference<T>(ThreadSafeReference.Object<T> reference) where T : IRealmObjectBase
Parameters
Type | Name | Description |
---|---|---|
ThreadSafeReference.Object<T> | reference | The thread-safe reference to the thread-confined IRealmObject/IEmbeddedObject to resolve in this Realm. |
Returns
Type | Description |
---|---|
T | A thread-confined instance of the original IRealmObject/IEmbeddedObject resolved for the current thread or |
Type Parameters
Name | Description |
---|---|
T | The type of the object, contained in the reference. |
ResolveReference<T>(Query<T>)
Returns the same query as the one referenced when the ThreadSafeReference.Query<T> was first created, but resolved for the current Realm for this thread.
Declaration
public IQueryable<T> ResolveReference<T>(ThreadSafeReference.Query<T> reference) where T : IRealmObjectBase
Parameters
Type | Name | Description |
---|---|---|
ThreadSafeReference.Query<T> | reference | The thread-safe reference to the thread-confined IQueryable<T> to resolve in this Realm. |
Returns
Type | Description |
---|---|
IQueryable<T> | A thread-confined instance of the original IQueryable<T> resolved for the current thread. |
Type Parameters
Name | Description |
---|---|
T | The type of the object, contained in the query. |
ResolveReference<T>(Set<T>)
Returns the same collection as the one referenced when the ThreadSafeReference.Set<T> was first created, but resolved for the current Realm for this thread.
Declaration
public ISet<T>? ResolveReference<T>(ThreadSafeReference.Set<T> reference)
Parameters
Type | Name | Description |
---|---|---|
ThreadSafeReference.Set<T> | reference | The thread-safe reference to the thread-confined ISet<T> to resolve in this Realm. |
Returns
Type | Description |
---|---|
ISet<T> | A thread-confined instance of the original ISet<T> resolved for the current thread or |
Type Parameters
Name | Description |
---|---|
T | The type of the elements, contained in the collection. |
Write(Action)
Execute an action inside a temporary Transaction. If no exception is thrown, the Transaction will be committed.
Declaration
public void Write(Action action)
Parameters
Type | Name | Description |
---|---|---|
Action | action | Action to execute inside a Transaction, creating, updating, or removing objects. |
Remarks
Creates its own temporary Transaction and commits it after running the lambda passed to action
.
Be careful of wrapping multiple single property updates in multiple Write(Action) calls.
It is more efficient to update several properties or even create multiple objects in a single Write(Action),
unless you need to guarantee finer-grained updates.
Examples
realm.Write(() =>
{
realm.Add(new Dog
{
Name = "Eddie",
Age = 5
});
});
|
Edit this page
View Source
WriteAsync(Action, CancellationToken)
Execute an action inside a temporary Transaction. If no exception is thrown, the Transaction will be committed. If the method is not called from a thread with a SynchronizationContext (like the UI thread), it behaves synchronously.
Declaration
public Task WriteAsync(Action action, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
Action | action | Action to execute inside a Transaction, creating, updating, or removing objects. |
CancellationToken | cancellationToken | Optional cancellation token to stop waiting to start a write transaction. |
Returns
Type | Description |
---|---|
Task | An awaitable Task that indicates that the transaction has been committed successfully. |
Examples
await realm.WriteAsync(() =>
{
realm.Add(new Dog
{
Breed = "Dalmatian",
});
});
|
Edit this page
View Source
WriteAsync<T>(Func<T>, CancellationToken)
Execute a delegate inside a temporary Transaction. If no exception is thrown, the Transaction will be committed. If the method is not called from a thread with a SynchronizationContext (like the UI thread), it behaves synchronously.
Declaration
public Task<T> WriteAsync<T>(Func<T> function, CancellationToken cancellationToken = default)
Parameters
Type | Name | Description |
---|---|---|
Func<T> | function | Delegate with one return value to execute inside a Transaction, creating, updating, or removing objects. |
CancellationToken | cancellationToken | Optional cancellation token to stop waiting to start a write transaction. |
Returns
Type | Description |
---|---|
Task<T> | An awaitable Task that indicates that the transaction has been committed successfully. The result of
the task is the result returned by invoking |
Type Parameters
Name | Description |
---|---|
T | The type returned by the input delegate. |
Examples
var dog = await realm.WriteAsync(() =>
{
return realm.Add(new Dog
{
Breed = "Dalmatian",
});
});
|
Edit this page
View Source
WriteCopy(RealmConfigurationBase)
Writes a compacted copy of the Realm to the path in the specified config. If the configuration object has non-null EncryptionKey, the copy will be encrypted with that key.
Declaration
public void WriteCopy(RealmConfigurationBase config)
Parameters
Type | Name | Description |
---|---|---|
RealmConfigurationBase | config | Configuration, specifying the path and optionally the encryption key for the copy. |
Remarks
- The destination file cannot already exist.
- When using a local Realm and this is called from within a transaction it writes the current data, and not the data as it was when the last transaction was committed.
Write<T>(Func<T>)
Execute a delegate inside a temporary Transaction. If no exception is thrown, the Transaction will be committed.
Declaration
public T Write<T>(Func<T> function)
Parameters
Type | Name | Description |
---|---|---|
Func<T> | function | Delegate with one return value to execute inside a Transaction, creating, updating, or removing objects. |
Returns
Type | Description |
---|---|
T | The return value of |
Type Parameters
Name | Description |
---|---|
T | The type returned by the input delegate. |
Remarks
Creates its own temporary Transaction and commits it after running the lambda passed to function
.
Be careful of wrapping multiple single property updates in multiple Write(Action) calls.
It is more efficient to update several properties or even create multiple objects in a single Write(Action),
unless you need to guarantee finer-grained updates.
Examples
var dog = realm.Write(() =>
{
return realm.Add(new Dog
{
Name = "Eddie",
Age = 5
});
});
Events
| Edit this page View SourceError
Triggered when a Realm-level exception has occurred.
Declaration
public event EventHandler<ErrorEventArgs>? Error
Event Type
Type | Description |
---|---|
EventHandler<ErrorEventArgs> |
RealmChanged
Triggered when a Realm has changed (i.e. a Transaction was committed).
Declaration
public event Realm.RealmChangedEventHandler? RealmChanged
Event Type
Type | Description |
---|---|
Realm.RealmChangedEventHandler |