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

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

    IsInTransaction

    Gets a value indicating whether there is an active Transaction is in transaction.

    Declaration
    public bool IsInTransaction { get; }
    Property Value
    Type Description
    Boolean

    true if is in transaction; otherwise, false.

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

    Methods

    | Improve this Doc View Source

    Add(RealmObject, Boolean)

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

    Declaration
    public RealmObject Add(RealmObject obj, bool update = false)
    Parameters
    Type Name Description
    RealmObject 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
    RealmObject

    The passed object.

    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. Cyclic graphs (Parent has Child that has a Parent) will result in undefined behavior. You have to break the cycle manually and assign relationships after all object have been 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

    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 : RealmObject
    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. Cyclic graphs (Parent has Child that has a Parent) will result in undefined behavior. You have to break the cycle manually and assign relationships after all object have been 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(String)

    Get a view of all the objects of a particular type.

    Declaration
    public IQueryable<dynamic> All(string className)
    Parameters
    Type Name Description
    String className

    The type of the objects as defined in the schema.

    Returns
    Type Description
    IQueryable<Object>

    A queryable collection that without further filtering, allows iterating all objects of className, in this realm.

    Remarks

    Because the objects inside the view are accessed dynamically, the view cannot be queried into using LINQ or other expression predicates.

    | 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 : RealmObject
    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()

    Factory for a write Transaction. Essential object to create scope for updates.

    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

    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

    CreateObject(String, Object)

    Factory for a managed object in a realm. Only valid within a write Transaction.

    Declaration
    public dynamic CreateObject(string className, object primaryKey)
    Parameters
    Type Name Description
    String className

    The type of object to create as defined in the schema.

    Object primaryKey

    The primary key of object to be created. If the object doesn't have primary key defined, this argument is ignored.

    Returns
    Type Description
    Object

    A dynamically-accessed Realm object.

    Remarks

    WARNING: if the dynamic object has a PrimaryKey then that must be the first property set otherwise other property changes may be lost.

    If the realm instance has been created from an un-typed schema (such as when migrating from an older version of a realm) the returned object will be purely dynamic. If the realm has been created from a typed schema as is the default case when calling GetInstance(RealmConfigurationBase) the returned object will be an instance of a user-defined class.

    Exceptions
    Type Condition
    RealmInvalidTransactionException

    If you invoke this when there is no write Transaction active on the Realm.

    ArgumentNullException

    If you pass null for an object with string primary key.

    ArgumentException

    If you pass primaryKey with type that is different from the type, defined in the schema.

    | Improve this Doc View Source

    DeleteRealm(RealmConfigurationBase)

    Deletes all the files associated with a realm.

    Declaration
    public static void DeleteRealm(RealmConfigurationBase configuration)
    Parameters
    Type Name Description
    RealmConfigurationBase configuration

    A RealmConfigurationBase which supplies the realm path.

    | 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(String, Nullable<Int64>)

    Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property.

    Declaration
    public RealmObject Find(string className, long? primaryKey)
    Parameters
    Type Name Description
    String className

    Name of class in dynamic situation.

    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
    RealmObject

    null or an object matching the primary key.

    Exceptions
    Type Condition
    RealmClassLacksPrimaryKeyException

    If the RealmObject class T lacks PrimaryKeyAttribute.

    | Improve this Doc View Source

    Find(String, String)

    Fast lookup of an object for dynamic use, from a class which has a PrimaryKey property.

    Declaration
    public RealmObject Find(string className, string primaryKey)
    Parameters
    Type Name Description
    String className

    Name of class in dynamic situation.

    String primaryKey

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

    Returns
    Type Description
    RealmObject

    null or an object matching the primary key.

    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 : RealmObject
    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 : RealmObject
    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>

    A Task<TResult> that is completed once the remote realm is fully synchronized or immediately if it's a local realm.

    Remarks

    If the configuration points to a remote realm belonging to a Realm Object Server the realm will be downloaded and fully synchronized with the server prior to the completion of the returned Task object. Otherwise this method behaves identically to GetInstance(RealmConfigurationBase) and immediately returns a completed Task.

    | 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(RealmObject)

    Removes a persistent object from this Realm, effectively deleting it.

    Declaration
    public void Remove(RealmObject obj)
    Parameters
    Type Name Description
    RealmObject 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(String)

    Remove all objects of a type from the Realm.

    Declaration
    public void RemoveAll(string className)
    Parameters
    Type Name Description
    String className

    Type of the objects to remove as defined in the schema.

    Exceptions
    Type Condition
    RealmInvalidTransactionException

    If you invoke this when there is no write Transaction active on the Realm.

    ArgumentException

    If you pass className that does not belong to this Realm's schema.

    | Improve this Doc View Source

    RemoveAll<T>()

    Remove all objects of a type from the Realm.

    Declaration
    public void RemoveAll<T>()
        where T : RealmObject
    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 : RealmObject
    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<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 : RealmObject
    Parameters
    Type Name Description
    ThreadSafeReference.Object<T> reference

    The thread-safe reference to the thread-confined RealmObject to resolve in this Realm.

    Returns
    Type Description
    T

    A thread-confined instance of the original RealmObject 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 : RealmObject
    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

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

    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
    public Task WriteAsync(Action<Realm> action)
    Parameters
    Type Name Description
    Action<Realm> action

    Action to perform 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 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

    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.

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

    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)
    PermissionExtensions.GetPrivileges(Realm)
    PermissionExtensions.GetPrivileges<T>(Realm)
    PermissionExtensions.GetPrivileges(Realm, String)
    PermissionExtensions.GetPrivileges(Realm, RealmObject)
    Subscription.GetAllSubscriptions(Realm)
    Subscription.UnsubscribeAsync(Realm, String)
    • Improve this Doc
    • View Source
    Back to top Copyright © 2020 Realm
    Generated by DocFX