Skip to main content

Session: Opening a Session

  • A Session object is obtained from the Document Store.

  • A Session can operate Synchronously or Asynchronously.

    • OpenSession() - Open a Session for a Synchrounous mode of operation.
    • OpenAsyncSession() - Open a Session for Asychrounous mode of operation.
  • Various Session options can be configured using the SessionOptions object.

  • Be sure to wrap the Session variable with a 'using' statement to ensure proper disposal.

  • If no database is specified then the Default Database (stored in the Document Store) is assumed.

  • In this page:

Syntax

OpenSession() / OpenAsyncSession() have three overloads:

// Open a Session for the default database configured in `DocumentStore.Database`
IDocumentSession OpenSession();

// Open a Session for a specified database
IDocumentSession OpenSession(string database);

// Open a Session and pass it a preconfigured SessionOptions object
IDocumentSession OpenSession(SessionOptions options);
ParameterTypeDescription
databasestringThe Session will operate on this database, overriding the default database set in the document store
optionsSessionOptionsAn object with Session configuration options. See details below
Return ValueDescription
IDocumentSession / IAsyncDocumentSessionInstance of a Session object

Session Options

The SessionOptions object contains various options to configure the Session's behavior.

OptionTypeDescriptionDefault Value
DatabasestringThe Session will operate on this database, overriding the Default Database.null - the Session operates on the Default Database
NoTrackingbooleanWhether the Session should track changes made to all entities that it has either loaded, stored, or queried on.
See Disable Tracking Example
false
NoCachingbooleanWhether the Session should cache the server responses.
See Disable Caching Example
false
RequestExecutorRequestExecutor(Advanced) The request executor the Session should usenull - the default request executor is used
TransactionModeTransactionModeSpecify the Session's transaction mode (SingleNode / ClusterWide).
See Cluster-Wide Transactions
SingleNode

Example

Here is an example of opening a Session using a SessionOptions object:

using (var store = new DocumentStore())
{
// Open a Session in synchronous operation mode for cluster-wide transactions

SessionOptions options = new SessionOptions
{
Database = "your_database_name",
TransactionMode = TransactionMode.ClusterWide
};

using (IDocumentSession Session = store.OpenSession(options))
{
// Run your business logic:
//
// Store documents
// Load and Modify documents
// Query indexes & collections
// Delete documents
// ... etc.

Session.SaveChanges();
}
}