Search Results for

    Show / Hide Table of Contents

    Class Realm

    A Realm instance (also referred to as a Realm) represents a Realm database.

    Inheritance
    Object
    Realm
    Implements
    IDisposable
    Namespace: Realms
    Assembly: Realm.dll
    Syntax
    public class Realm : IDisposable
    Remarks

    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.

    Properties

    | Improve this Doc View Source

    Config

    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.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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
    Boolean

    true if closed, false otherwise.

    | Improve this Doc View Source

    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
    Boolean

    true if the Realm is frozen and immutable; false otherwise.

    | Improve this Doc View Source

    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
    Boolean

    true if the Realm is in transaction; false otherwise.

    See Also
    BeginWrite()
    Transaction
    | Improve this Doc View Source

    Schema

    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.

    | Improve this Doc View Source

    Subscriptions

    Gets the SubscriptionSet representing the active subscriptions for this Realm.

    Declaration
    public SubscriptionSet Subscriptions { get; }
    Property Value
    Type Description
    SubscriptionSet

    The SubscriptionSet containing the query subscriptions that the server is using to decide which objects to synchronize with the local Realm. If the Realm was not created with a FlexibleSyncConfiguration, this will always be null.

    | Improve this Doc View Source

    SyncSession

    Gets the Session for this Realm.

    Declaration
    public Session SyncSession { get; }
    Property Value
    Type Description
    Session

    The Session that is responsible for synchronizing with MongoDB Atlas if the Realm instance was created with a SyncConfigurationBase; null otherwise.

    | Improve this Doc View Source

    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
    Boolean
    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 migraiton 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 noticable 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

    | Improve this Doc View Source

    Add<T>(T)

    This Realm will start managing a AsymmetricObject which has been created as a standalone object.

    Declaration
    public void Add<T>(T obj)
        where T : IAsymmetricObject
    Parameters
    Type Name Description
    T obj

    Must be a standalone AsymmetricObject, null not allowed.

    Type Parameters
    Name Description
    T

    The Type T must not only be a AsymmetricObject 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, AsymmetricObject will be managed. Once an AsymmetricObject becomes managed dereferencing any property of the original AsymmetricObject reference throws an exception.

    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.

    ObjectDisposedException

    If you invoke this method on a closed Realm.

    ArgumentNullException

    If you pass a null argument to this method.

    | Improve this Doc View Source

    Add<T>(T, Boolean)

    This Realm will start managing a RealmObject 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, null not allowed.

    Boolean update

    If true, and an object with the same primary key already exists, performs an update.

    Returns
    Type Description
    T

    The passed object, so that you can write var person = realm.Add(new Person { Id = 1 });.

    Type Parameters
    Name Description
    T

    The Type T must not only be a RealmObject 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.

    | Improve this Doc View Source

    Add<T>(IEnumerable<T>)

    Add a collection of standalone AsymmetricObjects to this Realm.

    Declaration
    public void Add<T>(IEnumerable<T> objs)
        where T : IAsymmetricObject
    Parameters
    Type Name Description
    IEnumerable<T> objs

    A collection of RealmObject instances that will be added to this Realm.

    Type Parameters
    Name Description
    T

    The Type T must not only be a AsymmetricObject 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 the collection will be managed. Once an AsymmetricObject becomes managed and the transaction is committed, dereferencing any property of the original AsymmetricObject reference throw an exeception. Hence, none of the properties of the elements in the collection can be deferenced anymore after the transaction.

    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.

    ObjectDisposedException

    If you invoke this method on a closed Realm.

    ArgumentNullException

    If you pass a null argument to this method.

    | Improve this Doc View Source

    Add<T>(IEnumerable<T>, Boolean)

    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 RealmObject instances that will be added to this Realm.

    Boolean update

    If true, and an object with the same primary key already exists, performs an update.

    Type Parameters
    Name Description
    T

    The Type T must not only be a RealmObject 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.

    | Improve this Doc View Source

    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 a RealmObject.

    | Improve this Doc View Source

    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();
    }
    | Improve this Doc View Source

    BeginWriteAsync(CancellationToken)

    Asynchronously begins a write transaction for this Realm.

    Declaration
    public async Task<Transaction> BeginWriteAsync(CancellationToken cancellationToken = default(CancellationToken))
    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();
    }
    | Improve this Doc 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
    Boolean

    true if successful, false if any file operation failed.

    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.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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()
    | Improve this Doc View Source

    Find<T>(Nullable<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
    Nullable<MongoDB.Bson.ObjectId> primaryKey

    Primary key to be matched exactly, same as an == search.

    Returns
    Type Description
    T

    null or an object matching the primary key.

    Type Parameters
    Name Description
    T

    The Type T must be a RealmObject.

    Exceptions
    Type Condition
    RealmClassLacksPrimaryKeyException

    If the RealmObject class T lacks PrimaryKeyAttribute.

    | Improve this Doc View Source

    Find<T>(Nullable<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
    Nullable<Guid> primaryKey

    Primary key to be matched exactly, same as an == search.

    Returns
    Type Description
    T

    null or an object matching the primary key.

    Type Parameters
    Name Description
    T

    The Type T must be a RealmObject.

    Exceptions
    Type Condition
    RealmClassLacksPrimaryKeyException

    If the RealmObject class T lacks PrimaryKeyAttribute.

    | Improve this Doc View Source

    Find<T>(Nullable<Int64>)

    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
    Nullable<Int64> primaryKey

    Primary key to be matched exactly, same as an == search. An argument of type long? works for all integer properties, supported as PrimaryKey.

    Returns
    Type Description
    T

    null or an object matching the primary key.

    Type Parameters
    Name Description
    T

    The Type T must be a RealmObject.

    Exceptions
    Type Condition
    RealmClassLacksPrimaryKeyException

    If the RealmObject class T lacks PrimaryKeyAttribute.

    | Improve this Doc View Source

    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

    null or an object matching the primary key.

    Type Parameters
    Name Description
    T

    The Type T must be a RealmObject.

    Exceptions
    Type Condition
    RealmClassLacksPrimaryKeyException

    If the RealmObject class T lacks PrimaryKeyAttribute.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    GetInstanceAsync(RealmConfigurationBase, CancellationToken)

    Factory for asynchronously obtaining a Realm instance.

    Declaration
    public static Task<Realm> GetInstanceAsync(RealmConfigurationBase config = null, CancellationToken cancellationToken = default(CancellationToken))
    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

    If the configuration is SyncConfigurationBase, the realm will be downloaded and fully synchronized with the server prior to the completion of the returned Task object. Otherwise this method will perform any migrations on a background thread before returning an opened instance to the calling thread.

    | Improve this Doc View Source

    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
    Boolean

    true if this instance is the same core instance; otherwise, false.

    Remarks

    You can, and should, have multiple instances open on different threads which have the same path and open the same Realm.

    | Improve this Doc View Source

    Refresh()

    Update the Realm instance and outstanding objects to point to the most recent persisted version.

    Declaration
    public bool Refresh()
    Returns
    Type Description
    Boolean

    Whether the Realm had any updates. Note that this may return true even if no data has actually changed.

    | Improve this Doc View Source

    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<Boolean>

    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.

    | Improve this Doc View Source

    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 obj is null.

    ArgumentException

    If you pass a standalone object.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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.

    | Improve this Doc View Source

    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 range is not the result of All<T>() or subsequent LINQ filtering.

    ArgumentNullException

    If range is null.

    | Improve this Doc View Source

    ResolveReference<TValue>(ThreadSafeReference.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 null if the set's parent object has been deleted after the reference was created.

    Type Parameters
    Name Description
    TValue

    The type of the values contained in the dictionary.

    | Improve this Doc View Source

    ResolveReference<T>(ThreadSafeReference.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 null if the list's parent object has been deleted after the reference was created.

    Type Parameters
    Name Description
    T

    The type of the objects, contained in the collection.

    | Improve this Doc View Source

    ResolveReference<T>(ThreadSafeReference.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 RealmObject/EmbeddedObject to resolve in this Realm.

    Returns
    Type Description
    T

    A thread-confined instance of the original RealmObject/EmbeddedObject resolved for the current thread or null if the object has been deleted after the reference was created.

    Type Parameters
    Name Description
    T

    The type of the object, contained in the reference.

    | Improve this Doc View Source

    ResolveReference<T>(ThreadSafeReference.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.

    | Improve this Doc View Source

    ResolveReference<T>(ThreadSafeReference.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 null if the set's parent object has been deleted after the reference was created.

    Type Parameters
    Name Description
    T

    The type of the elements, contained in the collection.

    | Improve this Doc View Source

    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
        });
    });
    | Improve this Doc View Source

    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 function.

    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
        });
    });
    | Improve this Doc 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(CancellationToken))
    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.

    Examples
    await realm.WriteAsync(() =>
    {
        realm.Add(new Dog
        {
            Breed = "Dalmatian",
        });
    });
    | Improve this Doc View Source

    WriteAsync(Action<Realm>)

    Execute an action inside a temporary Transaction on a worker thread, if called from UI thread. If no exception is thrown, the Transaction will be committed.

    Declaration
    [Obsolete("Use Realm.WriteAsync(Action action) instead.")]
    public Task WriteAsync(Action<Realm> action)
    Parameters
    Type Name Description
    Action<Realm> action

    Action to execute inside a Transaction, creating, updating, or removing objects.

    Returns
    Type Description
    Task

    An awaitable Task.

    Remarks

    Opens a new instance of this Realm on a worker thread and executes action inside a write Transaction. Realms and RealmObjects/EmbeddedObjects are thread-affine, so capturing any such objects in the action delegate will lead to errors if they're used on the worker thread. Note that it checks the SynchronizationContext to determine if Current is null, as a test to see if you are on the UI thread and will otherwise just call Write without starting a new thread. So if you know you are invoking from a worker thread, just call Write instead.

    Examples
    await realm.WriteAsync(tempRealm =>
    {
        var pongo = tempRealm.All<Dog>().Single(d => d.Name == "Pongo");
        var missis = tempRealm.All<Dog>().Single(d => d.Name == "Missis");
        for (var i = 0; i < 15; i++)
        {
            tempRealm.Add(new Dog
            {
                Breed = "Dalmatian",
                Mum = missis,
                Dad = pongo
            });
        }
    });

    Note that inside the action, we use tempRealm.

    | Improve this Doc 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 async Task<T> WriteAsync<T>(Func<T> function, CancellationToken cancellationToken = default(CancellationToken))
    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 with return type T.

    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",
        });
    });
    | Improve this Doc View Source

    WriteAsync<T>(Func<Realm, T>)

    Execute a delegate inside a temporary Transaction on a worker thread, if called from UI thread. If no exception is thrown, the Transaction will be committed.

    Declaration
    [Obsolete("Use Realm.WriteAsync(Func<T> function) instead.")]
    public async Task<T> WriteAsync<T>(Func<Realm, T> function)
    Parameters
    Type Name Description
    Func<Realm, T> function

    Delegate with one return value to execute inside a Transaction, creating, updating, or removing objects.

    Returns
    Type Description
    Task<T>

    An awaitable Task with return type T.

    Type Parameters
    Name Description
    T

    The type returned by the input delegate.

    Remarks

    Opens a new instance of this Realm on a worker thread and executes function inside a write Transaction. Realms and RealmObjects/EmbeddedObjects are thread-affine, so capturing any such objects in the action delegate will lead to errors if they're used on the worker thread. Note that it checks the SynchronizationContext to determine if Current is null, as a test to see if you are on the UI thread and will otherwise just call Write without starting a new thread. So if you know you are invoking from a worker thread, just call Write instead.

    Examples
    var dog = await realm.WriteAsync(tempRealm =>
    {
        return tempRealm.Add(new Dog
        {
            Breed = "Dalmatian",
        });
    });

    Note that inside the action, we use tempRealm.

    | Improve this Doc View Source

    WriteAsync<T>(Func<Realm, IList<T>>)

    Execute a delegate inside a temporary Transaction on a worker thread, if called from UI thread. If no exception is thrown, the Transaction will be committed.

    Declaration
    [Obsolete("Use Realm.WriteAsync(Func<T> function) instead.")]
    public async Task<IList<T>> WriteAsync<T>(Func<Realm, IList<T>> function)
    Parameters
    Type Name Description
    Func<Realm, IList<T>> function

    Delegate with return type IList<T> to execute inside a Transaction, creating, updating, or removing objects.

    Returns
    Type Description
    Task<IList<T>>

    An awaitable Task with return type IList<T>.

    Type Parameters
    Name Description
    T

    The type of data in the IList<T>.

    Remarks

    Opens a new instance of this Realm on a worker thread and executes function inside a write Transaction. Realms and RealmObjects/EmbeddedObjects are thread-affine, so capturing any such objects in the action delegate will lead to errors if they're used on the worker thread. Note that it checks the SynchronizationContext to determine if Current is null, as a test to see if you are on the UI thread and will otherwise just call Write without starting a new thread. So if you know you are invoking from a worker thread, just call Write instead.

    Examples
    var markDogs = await realm.WriteAsync(tempRealm =>
    {
        var mark = tempRealm.All<Person>().Single(d => d.Name == "Mark");
    
        mark.Dogs.Add(new Dog
        {
            Breed = "Dalmatian",
        });
    
        mark.Dogs.Add(new Dog
        {
            Breed = "Poodle",
        });
    
        return mark.Dogs;
    });

    Note that inside the action, we use tempRealm.

    | Improve this Doc View Source

    WriteAsync<T>(Func<Realm, IQueryable<T>>)

    Execute a delegate inside a temporary Transaction on a worker thread, if called from UI thread. If no exception is thrown, the Transaction will be committed.

    Declaration
    [Obsolete("Use Realm.WriteAsync(Func<T> function) instead.")]
    public async Task<IQueryable<T>> WriteAsync<T>(Func<Realm, IQueryable<T>> function)
        where T : IRealmObjectBase
    Parameters
    Type Name Description
    Func<Realm, IQueryable<T>> function

    Delegate with return type IQueryable<T> to execute inside a Transaction, creating, updating, or removing objects.

    Returns
    Type Description
    Task<IQueryable<T>>

    An awaitable Task with return type IQueryable<T>.

    Type Parameters
    Name Description
    T

    The type of data in the IQueryable<T>.

    Remarks

    Opens a new instance of this Realm on a worker thread and executes function inside a write Transaction. Realms and RealmObjects/EmbeddedObjects are thread-affine, so capturing any such objects in the action delegate will lead to errors if they're used on the worker thread. Note that it checks the SynchronizationContext to determine if Current is null, as a test to see if you are on the UI thread and will otherwise just call Write without starting a new thread. So if you know you are invoking from a worker thread, just call Write instead.

    Examples
    var dogs = await realm.WriteAsync(tempRealm =>
    {
        tempRealm.Add(new Dog
        {
            Breed = "Dalmatian",
        });
    
        tempRealm.Add(new Dog
        {
            Breed = "Poddle",
        });
    
        return tempRealm.All<Dog>();
    });

    Note that inside the action, we use tempRealm.

    | Improve this Doc 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
    1. The destination file cannot already exist.
    2. 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.
    3. When using Sync, it is required that all local changes are synchronized with the server before the copy can be written. This is to be sure that the file can be used as a starting point for a newly installed application. The function will throw if there are pending uploads.

    Events

    | Improve this Doc View Source

    Error

    Triggered when a Realm-level exception has occurred.

    Declaration
    public event EventHandler<ErrorEventArgs> Error
    Event Type
    Type Description
    EventHandler<ErrorEventArgs>
    | Improve this Doc View Source

    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

    Implements

    System.IDisposable

    Extension Methods

    RealmSyncExtensions.GetSession(Realm)
    • Improve this Doc
    • View Source
    In This Article
    Back to top Copyright © 2020 Realm
    Generated by DocFX