Transaction auto-wrapping for the data access layer
In this recipe, we'll show you how to 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 2, Models and Mappings.
How to do it…
Create a new class library named
Eg.Core.Data
.Install NHibernate to
Eg.Core.Data
using the NuGet Package Manager Console.Add the following two
DataAccessObject
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 WithinTransaction(() => session.Get<T>(id)); } public T Load(TId id) { return WithinTransaction(() => session.Load<T>(id)); } public void...