Implementing Fluent-nHibernate

To follow on from my short and brief post nHibernate mapping files no more, I have implemented fluent-nhibernate very successfully and easily in my own application. In this example I am going to implement the ApplicationUser, Title and Role domain entities. All my entities derived from a abstract class called EntityBase. This base class is very little, it holds an Id (int) property and an abstract method “IsValid()”.

public abstract class EntityBase
{
    private int id;

    protected EntityBase() : this(0) { }

    protected EntityBase(int id)
    {
        this.id = id;
    }

    public int Id
    {
        get { return this.id; }
    }

    public abstract bool IsValid();
}

I will start with the simplest class first being the Title class.

public class Title : EntityBase
{
    public string Name { get; set; }

    public override bool IsValid()
    {
        return !string.IsNullOrEmpty(Name);
    }
}

Before I do the mapping for the title class, I need to put the mappings in the right place. I have a Repository layer that contains all my repositories for all of my root entities. All of my repositories inherit from “EntityRepository” which is has a dependency on an implementation of IPersistenceRepository. This is my own interface that does not expose any leaky abstractions from a technology like nHibernate.

So getting to the point, I have an assembly called “RussellEast.Repositories” and a “RussellEast.Repositories.NHibernate” assembly which references the “RussellEast.Repositories” assembly as it holds the IPersistenceRepository interface. The “RussellEast.Repositories.NHibernate” has a class called “NHibernateRepository” which implements the IPersistenceRepository interface. The RussellEast.Repositories.NHibernate is the only assembly in my solution to know about nhibernate so I am going to place all my maps in this assembly under a folder called “Maps” and reference the Fluent-nHibernate assembly.

To implement Fluent-nhibernate there is not a need to use the repository pattern, I am a big fan of DDD so I do. I just wanted to explain where I was going to place my mappings as I don’t want them in my core application or in my domain model.  For my information on how I have created my repositories, please read my previous post Implementing the Repository and Finder patterns.

Enough with the ramblings, here is the mapping for the Title entity

using FluentNHibernate;
using FluentNHibernate.Mapping;
using RussellEast.Domain.People;

namespace RussellEast.Repositories.NHibernate.Maps.People
{
    public class TitleMap : ClassMap<Title>
    {
        public TitleMap()
        {
            Id(x => x.Id).Access
                .AsReadOnlyPropertyThroughLowerCaseField()
                .GeneratedBy.Identity();

            Map(x => x.Name).CanNotBeNull().WithLengthOf(20);
        }
    }
}

If you can see from the TitleMap, I am mapping the Id to my Id readonly property in my EntityBase class that the Title entity derives from. The Fluent interface allows me to set up the access for nhibernate to populate it and generation for my Id. The Map method wires up the Name property and sets the field size and not null constaint. (sorry for stating the obvious).

Now for the Role Entity.

public class Role : EntityBase
{
    public string Name { get; set; }
    public bool IsSystemRole { get; set; } 

    public override bool IsValid()     
    { 
        return !string.IsNullOrEmpty(Name);
    }
}

Not much different from the Title Entity, just the additional “IsSystemRole” property. Here is the mapping class.

public class RoleMap : ClassMap<Role>
{
    public RoleMap()
    {
        Id(x =>x.Id).Access
            .AsReadOnlyPropertyThroughLowerCaseField()
            .GeneratedBy.Identity();
        Map(x =>x.Name).CanNotBeNull().WithLengthOf(50);
        Map(x => x.IsSystemRole);
    }
}

This is similar to the TitleMap, so not much to learn here. So now to the ApplicationUser entity. An ApplicationUser is a person, i have other domain entities in my application that are people, so i have an Person entity.

using System.Text.RegularExpressions;

namespace EWS.Portcullis.Domain.People
{
    public abstract class Person : EntityBase
    {
        private string email;

        public Title Title { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string Email
        {
            get { return email; }
            set 
            {
                if (IsEmailValid(value))
                {
                    email = value;
                }
            }
        }

        protected bool IsEmailValid(string value)
        {
            const string pattern = @"^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$";

            bool isValid = true;

            if (!string.IsNullOrEmpty(value))
            {
                Regex regex = new Regex(pattern);

                isValid = regex.IsMatch(value);
            }

            return isValid;
        }
    }
}

My ApplicationUser entity derives from Person

    public class ApplicationUser : Person
    {
        public string LoginName {get; set;}
        public int Salt { get; set; }
        public string Password { get; set; }
        public DateTime LastLoggedIn { get; set; }
        public Guid Token { get; set; }
        public IEnumerable Roles { get; set; }

        public override bool IsValid()
        {
            return (!(string.IsNullOrEmpty(FirstName) 
                || string.IsNullOrEmpty(LastName)));
        }
    }

My ApplicationUserMap looks like this.

    public class ApplicationUserMap : ClassMap
    {
        public ApplicationUserMap()
        {
            Id(x => x.Id).Access
                .AsReadOnlyPropertyThroughLowerCaseField()
                .GeneratedBy.Identity();
            Map(x => x.FirstName).CanNotBeNull().WithLengthOf(100);
            Map(x => x.LastName).CanNotBeNull().WithLengthOf(100);
            Map(x => x.Email).WithLengthOf(100);
            Map(x => x.LoginName).WithLengthOf(50);
            Map(x => x.Password).WithLengthOf(255); 
            Map(x => x.Salt);
            Map(x => x.LastLoggedIn);
            Map(x => x.Token);
            References(x => x.Title);
            HasManyToMany(x => x.Roles).AsBag();
        }
    }

As you will see, I use the References method to map the Title association. As for Roles, I have an ApplicationUser that can belong to many Roles and a Role can have many ApplicationUsers. I define this association using the HasManyToMany method and set as “AsBag”. This works great as my Role property in the ApplicationUser is type of IEnumerable. This is nice side effect here is that I don’t have to have a specialised collection type like “ISet” in my domain layer.

The final bit of code needed is to configure NHibernate which is shown in the code snippet below.

private static readonly ISessionFactory sessionFactory;
private ISession currentSession;

static NHibernateSessionLocator()
{
    sessionFactory = GetConfiguration().BuildSessionFactory();
}

private static Configuration GetConfiguration()
{
     Configuration cfg = new Configuration().Configure();

     string mappingAssembly = ConfigurationManager
          .AppSettings["NHibernate.Mapping.Assembly"];

      var persistenceModel = new PersistenceModel();

      persistenceModel
           .addMappingsFromAssembly(Assembly.Load(mappingAssembly));
      persistenceModel.Configure(cfg);

      return cfg;
}
        
public ISession ActiveSession()
{
     if (currentSession == null)
     {
         currentSession = sessionFactory.OpenSession();
     }

      return currentSession;
}

public void CloseActiveSession()
{
	...
}

public void UpdateDatabaseSchema()
{
     Configuration cfg = GetConfiguration();

     SchemaUpdate schemaUpdate = new SchemaUpdate(cfg);

     schemaUpdate.Execute(true, false);
}

The UpdateDatabaseSchema method is not part of my application but when i add a new entity and Map to my application i run this method from debug mode as it outputs the SQL DDL commands to the output window, which i use to create my tables. Here is a snippet of my application config file:

<appSettings>
    <add key="NHibernate.Mapping.Assembly" 
        value="RussellEast.Repositories.NHibernate"/>
</appSettings>

Using fluent-nhibernate has made my life so much easier.  I applaud the developers that created this.

Advertisements

Implementing the Repository and Finder patterns

Introduction

Over the last year I have been developing my own application using Domain Driven Design (DDD). I am also working on products in my day job that uses DDD. In the last month, myself and my fellow developers that I work with, went on a little journey to find the right way to implement the repository pattern including queries. My fellow devs and I wanted a solution to achieve the following goals:

  • A solid OO approach that was not bound to a specific technology. Meaning that we could develop this in C# or Java or what ever language.
  • No leaky abstraction. For example, we are using nHibernate at the moment, but in the future we might choose to use a different Object Relational Mapper (ORM). We don’t want our Repository or Finder interface to expose Nhibernate interfaces like “ISession” or “ICriteria”.
  • A repository per aggregate root.
  • No code duplication
  • Fully testable, driven out by our unit tests and me able to mock out the dependancies.
  • Friendly to our Inversion of Control (IoC) framework (ninject, spring.net and castle Windsor etc)
  • Provide a fluent interface to our repositories.

None of us are new to the Repository pattern or ways to implement query objects, so we all have ideas and existing code for tackling this. Combined we come up with this.

In my own application, my implementation used extension methods, its worked well, but because extension methods are static, i had no way of mocking them out  with Rhino mocks. This was not a showstopper, but meant that when i was writing unit tests in my service layer for example i have to set up the data to satisfy the logic in the extension methods.

Throughout the rest of this post, i will be using code from my own application.

The desired result


Here is an example of how we intent to use our repositories:


ApplicationUser user = applicationUserRepository
    .Find.ByLoginName(request.LoginName);

As you can see the repository has a find property on it that exposes a  ByLoginName method that takes a string argument and returns a single ApplicationUser object.

Entity Implementation


The ApplicationUser is a Entity, all of my Entities inherit from a base class called EntityBase:

public abstract class EntityBase
{
    private int id; 

    protected EntityBase() : this(0) { } 

    protected EntityBase(int id)
    {
        this.id = id;
    } 

    public int Id
    {
        get { return this.id; }
    } 

    public abstract bool IsValid();

    ...
}

Not much to it this, all my entities have an identity and i want all my entities to be able to state if the data they contain is valid

Repository Implementation

All of my repositories extend a base IRepository interface.

public interface IRepository<T> where T : EntityBase
{
    T Get(int id);
    void Save(T entity);
}

As you can see the generic type is constrained by the EntityBase type. The IRepository interface is not used directly outside of my repository layer, but is extended by the typed Repository interfaces:

public interface IApplicationUserRepository : IRepository<ApplicationUser>
{
    IApplicationUserFinder Find { get; }
}

In my application, I use dependency injection so my repositories are injected using the typed interface.  IApplicationUserRepository has one member being the Finder interface (more on that below).

One of my objectives was to remove duplicate code, in my effort to do this, i have an abstract class in which all my repositories inherit from.

public abstract class EntityRepository<T> : IRepository<T> where T : EntityBase
{
    protected readonly IPersistanceRepository repository;

    public EntityRepository(IPersistanceRepository repository)
    {
       this.repository = repository;
    }     

    public virtual T Get(int id)
    {
       return repository.Get<T>(id);
    } 

    public virtual void Save(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        } 

        if (entity.IsValid())
        {
             repository.Save(entity);
        }
    } 

     protected IQueryable<T> Query()
     {
         return repository.Query<T>();
     }

 }

This class must be supplied an instance of IPersistanceRepository.  Here is the IPersistanceRepository interface

public interface IPersistanceRepository
{
    T Get<T>(int id);
    void Save<T>(T entity);
    IQueryable<T> Query<T>();
}

A concrete implementation of the  IPersistanceRepository interface is the technology / ORM specific stuff. I am using NHibernate 2.0, so my concrete implementation is called “NHibernateRepository”. By using the IPersistanceRepository interface i am keeping the specifics abstracted away inside the concrete class. I have been able to successfully swap my IPersistanceRepository instance from NHibernate to a DB4o implementation with ease and no effect to my repositories.

Finder Implementation

Like the IRepository interface is used as a base interface, i also have a base IEntityFinder interface which again is not directly used outside of my repository layer.

public interface IEntityFinder<T> where T : EntityBase
{
    IQueryable<T> DataSource { set; }
}

As you can see, the interface has a DataSource property of IQueryable, the reason for this is that I am using System.Linq in my project which I will come onto later. But its purpose is to give the Finder a datasource. Now for the IApplicationUserFinder interface.

public interface IApplicationUserFinder : IEntityFinder<ApplicationUser>
{
    ApplicationUser ByLoginName(string loginName);

    ApplicationUser ByToken(Guid token);
}

The typed Repository

Now for my implementation of my typed Repository.

public class ApplicationUserRepository : EntityRepository<ApplicationUser>, IApplicationUserRepository
{
    private readonly IApplicationUserFinder finder; 

    public ApplicationUserRepository(IPersistanceRepository repository, IApplicationUserFinder finder)
        : base(repository)
    {
        this.finder = finder; 

        this.finder.DataSource = Query();
    } 

    public IApplicationUserFinder Find
    {
        get { return finder; }
    }
}

This repository derives from EntityRepository and implements IApplicationUserRepository. Its constucted with its dependencies being injected. The Finder instance has it datasource set to IQuerable<ApplicationUser>.

The typed finder

using System.Collections.Generic;
using System.Linq;

public class ApplicationUserFinder : IApplicationUserFinder
{
    private IQueryable<ApplicationUser> users; 

    public IQueryable<ApplicationUser> DataSource
    {
        set { users = value; }
    } 

    public ApplicationUser ByLoginName(string loginName)
    {
        if (string.IsNullOrEmpty(loginName))
        {
            throw new ArgumentNullException("loginName");
        } 

        return users.Where(u => u.LoginName == loginName).FirstOrDefault();
    } 

    public ApplicationUser ByToken(Guid token)
    {
        return users.Where(u => u.Token == token).FirstOrDefault();
    }
}

What do we have then

We have our entity, repository and Finder created. The repository and Finder have typed interfaces, which means i can wire these up in my IoC container. My IEntityFinder interface sort of went against my goal of no leaky abstraction as its using System.Linq, but i think i can live with myself. By having my finder implement an interface i could have different concrete implementations.

My finder is returning a single instance of ApplicationUser. I could have finder methods that return Iquerable that allows for method chaining etc. Plus i have not allowed for “And”, “Or” or “Not” as that is a different topic. But i have a base to work on.

nibernate repository

To be more code complete here is a snippet of my NHibernate repository that returns the initial query. I am using nhibernate 2.0 with nhibernate.linq.

    using System.Linq;
    using NHibernate;
    using NHibernate.Linq;

    public class NHibernateRepository  : IPersistanceRepository
    {
        private readonly ISessionLocator sessionLocator;

        public NHibernateRepository(ISessionLocator sessionLocator)
        {
            this.sessionLocator = sessionLocator;
        }

        public T Get<T>(int id)
        {
            ISession session = sessionLocator.ActiveSession();

            return session.Get(id);
        }

        public void Save<T>(T entity)
        {
             ...
        }

        public IQueryable<T> Query<T>()
        {
            var qry = from t in sessionLocator.ActiveSession().Linq()
                      select t;

            return qry.AsQueryable();
        }
    }

The beauty of this that the NHibernate specific code is in one place, my repositories and finders have no knowledge of nhibernate. In my finders, i am using linq for objects and lambda’s for my logic. Because i am using IQuerable, i can build up the query through my finders and the execution is deferred until i call a method like “ToList” or “First” etc. The queryProvider in nhibernate.linq builds the sql statement and hits the database once with the specific query.

Finally a big thank you to Neil Martin and Tim Escott for their involvement on this. Please read this post “Creating Fluent finders and repositories part 1 which continues from this post.

My quest for the holy grail of data access. The story so far

My holy grail is finding the right solution for working with database / persistence technologies. Looking back at over my career (all 13 years of it) I have been on this quest for most of it, but more actively in my .Net years. Before .NET I used be a VB/ASP guy using SQL Server  and database access was easy, ADO commands and recordsets talking to stored procedures (sprocs),  it was simple building applications in a data centric manor.  Then .NET 1.0, I jumped straight into .NET and ADO.NET from one of the early beta’s . Microsoft brought datasets to the table (or tables to the dataset) that changed the way we went about accessing data from a data store. By .net 1.1, I favoured data-readers over datasets, but my real concerns at this point was about the many lines of duplicate code I was writing. Here was the key moment.

The search started for a database access framework that removed the duplicated ADO.Net and kept data access in its own layer and generally make my life easier. I had mainly been developing applications using MS SQL server so sprocs were the API to the database and always a must do (every developer and DBA I worked with and knew had brought into the fact that sprocs were the right way to communicate with MS SQL server and would laugh at anyone who thought different). I had at the time reviewed code generation tools that I could point at my database tables and after watching a lovely progress bar, produced all my sprocs for CRUD behaviour accompanied by a C# class file for each table in my database. Although it worked and built a big percentage of an application for me, it was very procedural and still was not satisfied with it as a solution.

I then developed 2 different applications to address this. My first attempt was to create a business object template and a stored procedure template, then write my own code generator to fill in the gaps. This did work, but was still to procedural. My second app was to use an Aspect Oriented approach using reflection. This also worked and I was very proud of my creation. I showed this to a couple of developers I was working with at the time and they slammed it and I took it to heart. Looking back at this now, I wish I took their criticism with a pinch of salt as they showed me no better alternative and now I know they opinions were wrong. Effectively I development my own Castle ActiveRecord sitting on top of ADO.NET using sprocs.

Along came .NET 2005, along side digging deep into the world of OO, Java, design patterns, Agile, TDD, XP  and all the new stuff in C# 2005. My data access quest was still unfinished so I entered the quest again. There was huge amount of business application frameworks on the market. I reviewed and experimented with many frameworks from the Enterprise data access block, .Net tiers, CSLA etc. I still felt that I was on a false trail.

From the start of my quest in the .net age to where I was in 2005, my goals had changed. I no longer brought into the belief that sproc’s are truly wonderful and all the other propaganda around them. I developed my application around the domain problem not the database schema. In fact, I didn’t even care what my database technology was. I finally found Object Relational Mapping (ORM) as the right way to address my needs.

Thinking that my quest was coming to an end I faced a new problem . I was working in Microsoft shops and although I brought into ORM, no one else did. Trying to educate people came with resistance. Some people believe what they once learned, and are closed minded to new ideas and generally don’t question their current methods.  This problem spanned into another problems:

  1. Gaining ORM experience in a commercial project becomes hard to get.
  2. The problem is not just getting ORM buy in from others in the business, but getting people to think  “domain centric” instead of a “data centric” .

I had to admit, faced with these problems I was close to jumping out of land of Microsoft and into the world of Java where ORM and many other development approaches are openly encouraged. Before I jumped the fenced, the whispering of LINQ and WPF has kept my feet in the land of Microsoft. Knowing that Microsoft will be releasing their own ORM tool the commercial uptake of ORM will increase in time as it did with TDD and MSTest. Happier times lie ahead.

Its 2008, I practice Domain Driven Design (DDD) and have been building up my experience in nHibernate (I found learning Castle ActiveRecord first a good help). I am working with nHibernate in my day job and in my opinion nHibernate is still the powerhouse ORM for .NET. I have used Linq for SQL and I think its a good starting point for developers getting into ORM but nHibernate suites Domain Driven Design out of the box, you can bend Linq for SQL for DDD by using mapping files to kept for domain objects persistent ignorant as well as using the Repository pattern but its still second place to nHibernate. Linq for Entity has been long awaited, its big product it still too early for me to pass judgement.

NHibernate is still not perfect, working with XML mapping files is not fun. I have been using Fluent-nHibernate which replaces the XML mappings with lambda’s and has a DSL for creating a map for you entities. Creating queries with DetachedCriteria is not as nice as writing a linq query but if you achieve this with nNibernate.Linq.

I think i have found my holy grail (at last) using Fluent-nHibernate , Linq for Objects and nNibernate.Linq with the Repository and Finder pattern, which I will be providing code examples in my next post.

nHibernate mapping files no more

During an evenings coding, I ran into a typical problem with an nhibernate mapping file, (it was a spelling mistake) I had one of those moments when you go onto google to see if any one has come up with something smart to tackle this. I design from the the domain model  first so i was not looking for a code generator that you point at a database and way it goes. I was looking for a OO approach to this that removed xml from the mix.

It was a successful google search, I came across Fluent-NHibernate.

This sample code snippet was enough to stop my search and get me excited.

public CustomerMap : ClassMap<Customer>
{
  public CustomerMap()
  {
    Id(x => x.ID);
    Map(x => x.Name);
    Map(x => x.Credit);
    HasMany<Product>(x => x.Products)
      .AsBag();
    Component<Address>(x => x.Address, m =>
    {
        m.Map(x => x.AddressLine1);
        m.Map(x => x.AddressLine2);
        m.Map(x => x.CityName);
        m.Map(x => x.CountryName);
    });
}

What appeals to me about this code above:

  • The fluent interface and the use of lambda’s makes it very readable.
  • As its a class, I can group all my map objects into a single assembly. Then let the concerning layer in my application reference it, keeping my domain model persistent ignorant. (Before I came across “Fluent nHibernate” I was going to resort to using attributes)
  • Thinking ahead, when/if I refactor my entities, resharper will also make changes to map objects.
  • I am a TDD/BDD practitioner, Its an object, i want to put my mapping logic under test.
  • Lastly, no need for xml mapping files any more.

So I read some more, downloaded the code and had a play.

You can get an idea of how this works in about 5 minutes by running the quick start. The instructions and general documentation on this site is a little light on the ground and not much more info on the web at the moment to give more depth on the usage of this API.  The quick start uses a Cat object as the entity to persist.  I don’t really come across to many cats, dogs or other animals in programming so I wanted to used a real life example to get a better feel for it. At the moment to get assemblies, you need to checkout the code from the svn truck and compile the code yourself.

Running the Quick start

To aid the quick start instructions

  1. Create a new folder on PC and checkout the code from the SVN trunk “http://code.google.com/p/fluent-nhibernate/source/checkout&#8221;.
  2. From your working folder. Open up the quickStart solution and build it.
  3. As the context is ORM you need a database to push and pull data from. I had an instance of sql express to hand, so I created a blank database called “test”.
  4. Back to Visual studio, in the “FluentNNibernate.QuickStart” project, change the connection string in the app.config to point to your database.
  5. The quick start does not have an UI to use, but its behavior is expressed in the integration tests. Open up “QuickStartTester.cs”, find the “Export_Schema” method (which is decorated with the Explicit nunit attribute) and run the test (I used Test driven .net to run the test). This will create a new table in your database.
  6. Now run the “Can_Persist_Cat” test method. This tests creates an instance of Cat, populates it and saves, it. Lastly the test, pulls the data from the database by the id and compares the ids.

This is a very simple test but enough to wet my appetite. I have a working example using more business like entities on this post here Implementing Fluent-nHibernate.