Book Image

NHibernate 3.0 Cookbook

By : Jason Dentler
Book Image

NHibernate 3.0 Cookbook

By: Jason Dentler

Overview of this book

<p>NHibernate is an innovative, flexible, scalable, and feature-complete open source project for data access. Although it sounds like an easy task to build and maintain database applications, it can be challenging to get beyond the basics and develop applications that meet your needs perfectly.<br /><br />The NHibernate Cookbook explains each feature of NHibernate 3.0 in detail through example recipes that you can quickly apply to your applications. Set yourself free from stored procedures and inline SQL. Quite simply, if you build .NET applications that use databases, this book is for you.<br /><br />The book will take you from the absolute basics of NHibernate through its most advanced features and beyond, showing you how to take full advantage of each concept to quickly create amazing database applications. Beginners will learn several techniques for each of the 4 core NHibernate tasks – mapping, configuration, session &amp; transaction management, and querying – and which techniques fit best with various types of applications. In short, you will be able to build an application using NHibernate. Intermediate level readers will learn how to best implement enterprise application architecture patterns using NHibernate, leading to clean, easy-to-understand code, and increased productivity. In addition to new v3.0 features, advanced readers will learn creative ways to extend NHibernate core, as well as techniques using the NHibernate search, shards, spatial, and validation projects.</p>
Table of Contents (15 chapters)
NHibernate 3.0 Cookbook
Credits
About the Author
About the Reviewers
Preface
Index

Transaction Auto-wrapping for the data access layer


In this recipe, I'll show you how we can set up the data access layer to wrap all data access in NHibernate transactions automatically.

Getting ready

Complete the Eg.Core model and mappings from Chapter 1.

How to do it...

  1. Create a new class library named Eg.Core.Data.

  2. Add a reference to NHibernate.dll and the Eg.Core project.

  3. Add the following two DAO classes:

    public class DataAccessObject<T, TId>
      where T : Entity<TId>
    {
    
      private readonly ISessionFactory _sessionFactory;
    
      private ISession session
      {
        get
        {
          return _sessionFactory.GetCurrentSession();
        }
      }
    
      public DataAccessObject(ISessionFactory sessionFactory)
      {
        _sessionFactory = sessionFactory;
      }	
    
      public T Get(TId id)
      {
        return Transact(() => session.Get<T>(id));
      }
    
      public T Load(TId id)
      {
        return Transact(() => session.Load<T>(id));
      }
    
      public void Save(T entity)
      {
        Transact(() => session.SaveOrUpdate...