The main runtime interface between a .NET application and NHibernate. This is the central API class abstracting the notion of a persistence service.

Namespace: NHibernate
Assembly: NHibernate (in NHibernate.dll) Version: 3.2.0.4000 (3.2.0.4000)

Syntax

C#
public interface ISession : IDisposable
Visual Basic
Public Interface ISession _
	Inherits IDisposable
Visual C++
public interface class ISession : IDisposable

Remarks

The lifecycle of a ISession is bounded by the beginning and end of a logical transaction. (Long transactions might span several database transactions.)

The main function of the ISession is to offer create, find and delete operations for instances of mapped entity classes. Instances may exist in one of two states:

  • transient: not associated with any ISession
  • persistent: associated with a ISession

Transient instances may be made persistent by calling Save(), Insert(), or Update(). Persistent instances may be made transient by calling Delete(). Any instance returned by a List(), Enumerable(), Load(), or Create() method is persistent.

Save() results in an SQL INSERT, Delete() in an SQL DELETE and Update() in an SQL UPDATE. Changes to persistent instances are detected at flush time and also result in an SQL UPDATE.

It is not intended that implementors be threadsafe. Instead each thread/transaction should obtain its own instance from an ISessionFactory.

A ISession instance is serializable if its persistent classes are serializable

A typical transaction should use the following idiom:

CopyC#
using (ISession session = factory.OpenSession())
using (ITransaction tx = session.BeginTransaction())
{
    try
    {
        // do some work
        ...
        tx.Commit();
    }
    catch (Exception e)
    {
        if (tx != null) tx.Rollback();
        throw;
    }
}

If the ISession throws an exception, the transaction must be rolled back and the session discarded. The internal state of the ISession might not be consistent with the database after the exception occurs.

See Also