Getting Started with SQLite and Loquacious NHibernate 3.2

After I figured out how to create and access a SQLite database in C#, the obvious (for me, at least) next step was to use NHibernate for database access.

In NH 2.1.2 GA I preferred the Fluent configuration rather than the XML-based HBM files, which has been replaced by Loquacious. (You can read more on Loquacious here and here.)

You start with classes which represent a table (or view), and class maps that define the mapping of table fields to class properties:

public partial class DirectorySelection
  public virtual int ID { get; protected set; }
  public virtual string Path { get; set; }
public partial class DirectorySelection_Map 
  : ClassMapping<DirectorySelection>
  public DirectorySelection_Map()
    Id(x => x.ID, map =>
    Property(x => x.Path, map =>

Class maps require the inclusion of NH namespaces NHibernate.Mapping.ByCode and NHibernate.Mapping.ByCode.Conformist.

Next, we need to define a Session Factory which will create us a NH Session every time we access the database:

  public class ConfigureNH
    static ISessionFactory sessionFactory = NHSessionFactory();

    static ISessionFactory NHSessionFactory()
      var mapper = new ModelMapper();
      HbmMapping domainMapping = 

      var f = Path.Combine(
      var cn = 
        (new System.Data.SQLite.SQLiteConnectionStringBuilder { DataSource = f })

      var configuration = new NHibernate.Cfg.Configuration();
      configuration.DataBaseIntegration(c =>
        c.ConnectionString = cn;
        c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
        c.SchemaAction = SchemaAutoAction.Update;    

        c.LogFormattedSql = true;
        c.LogSqlInConsole = true;
      sessionFactory = configuration.BuildSessionFactory();
      return sessionFactory;

    public static ISessionFactory SessionFactory
        return sessionFactory;

Note that this configuration class needs to be contained in the same assembly as the NH data classes and maps, since we use Assembly.GetExecutingAssembly().GetExportedTypes() to retrieve all DAL classes.

To create an NH session, we simply open one via the session factory:

var session = ConfigureNH.SessionFactory.OpenSession();

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.