Setting up an NHibernate repository
Many developers prefer the repository pattern to data access objects. In this recipe, we will show you how to set up the repository pattern with NHibernate.
Getting ready
Set up the Eg.Core
project with the model and mappings from Chapter 2, Models and Mappings.
How to do it…
Create a new and empty class library project named
Eg.Core.Data
.Add a reference to
Eg.Core
project in Chapter 2, Models and Mappings.Add the following
IRepository
interface:public interface IRepository<T>: IEnumerable<T> where T : Entity { void Add(T item); bool Contains(T item); int Count { get; } bool Remove(T item); }
Create a new and empty class library project named
Eg.Core.Data.Impl
.Add references to the
Eg.Core
andEg.Core.Data
projects.Add a new abstract class named
NHibernateBase
using the following code:protected readonly ISessionFactory _sessionFactory; protected virtual ISession session { get { return _sessionFactory.GetCurrentSession(); ...