December 19, 2012

'Hello World' of the NHibernate world

This is the simplest "'Hello World' for NHibernate" example I could come up with. There are different approaches to configuring NHibernate and performing mappings, but this is a code-first approach which has many advantages - not the least of which is simplicity.

1. Start with an entity that you want to persist to a database

public class Customer
  public virtual Guid Id { get; set; }
  public virtual string Name { get; set; }

2. Next, configure NHibernate for your database (Microsoft SQL Server 2008 in this example, although many others are supported)

var configuration = new Configuration();
    .Connected.Using(...your connection string...);

3. Create a mapping for the Customer entity

The mapping tells NHibernate how to map entity properties to database table columns.

var mapper = new ModelMapper();
mapper.Class<Customer>(rc =>
    rc.Id(x => x.Id, m => m.Generator(Generators.Guid));
    rc.Property(x => x.Name);

There are a number of other ways to map an entity (e.g. XML, Fluent NHibernate), but here we use 'by code' mapping which is a convention-based approach. This expects an underlying database table called Customer, with columns 'Id' and 'Name', to exist. If required, NHibernate can even create this schema for you. See the GIST associated with this post.

4. Add the mapping to the NHibernate configuration

var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

All the hard work is done. Time to sit back and let NHibernate take care of the rest. For example, to persist a new Customer entity:

using (var sessionFactory = configuration.BuildSessionFactory())
    using (var session = sessionFactory.OpenSession())
        var customer = new Customer { Name = "Aristotle" };

You should be able to have this up and running in Visual Studio in a matter of minutes. Here is a GitHub GIST to get you started.

No comments:

Post a Comment