Skip to main content

Session: Opening a session

To open synchronous session use OpenSession method from DocumentStore or OpenAsyncSession if you prefer working in asynchronous manner.

Syntax

There are three overloads of OpenSession method

// 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);

First method is a equivalent of doing

using (var store = new DocumentStore())
{
// The first overload -
store.OpenSession();
// - is equivalent to:
store.OpenSession(new SessionOptions());

// The second overload -
store.OpenSession("your_database_name");
// - is equivalent to:
store.OpenSession(new SessionOptions
{
Database = "your_database_name"
});
}

Second method is a equivalent of doing

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();
}
}
Parameters
optionsOpenSessionOptionsOptions containing information such as name of database on which session will work and credentials that will be used.
Return Value
IDocumentSessionInstance of a session object that implements IDocumentSession interface.

Example I

using (IDocumentSession Session = store.OpenSession())
{
// code here
}

Example II

using (IAsyncDocumentSession Session = store.OpenAsyncSession())
{
// async code here
}

Remarks

Always remember to release session allocated resources after usage by invoking Dispose method or wrapping session object in using statement.