Using Fluent NHibernate for XML-Free Class Mapping

NHibernate, the lightweight object relational mapping (ORM) tool for .NET, has a statically compiled counterpart called Fluent NHibernate. In essence, Fluent NHibernate is a XML-less, compile safe, automated NHibernate mapper that provides support for LINQ on top of NHibernate as well as an alternative to NHibernate’s standard XML mapping.

In this article I will discuss the basics of Fluent NHibernate, how to get started using it, and how you can implement various types of mappings in your .NET applications using this lightweight ORM tool.

To use the code examples illustrated in this article, you should have Visual Studio 2008 or higher installed on your system. You should also have the necessary NHibernate and Fluent NHibernate assemblies available. You can download them from the Fluent NHibernate webpage.

Getting Started with Fluent NHibernate

To get started with Fluent NHibernate, you need to create a new project in Visual Studio 2010 and then add the necessary assemblies. The following sample program lists those assemblies and also illustrates how you can open a connection to your SQL Server database using Fluent NHibernate. This class acts as a wrapper on top of Fluent NHibernate.

using FluentNHibernate;using NHibernate;using FluentNHibernate.Cfg.Db;using FluentNHibernate.Automapping;using NHibernate.Cfg;using NHibernate.Tool.hbm2ddl;using System.Reflection;namespace Test{    public static class FluentNHibernateGateway    {        private static ISessionFactory _sessionFactory = null;        private static readonly string _businessObjectsNamespace = "Test.BusinessEntity.Mappings";        private static readonly string _connectionString = @"Data Source=JOYDIP-PCSQLServer2008;Initial Catalog=Sample;Integrated Security=True";        private static ISessionFactory SessionFactory        {            get            {                if (_sessionFactory == null)                {//Code to create a new session factory //using the persistence model and loading the // business entities from the namespace //specified earlier in this program.                }                return _sessionFactory;            }        }        public static ISession OpenSession()        {            return SessionFactory.OpenSession();        }    }}

Now, to open a connection and get started, you would call FluentNHibernateGateway.OpenSession();.

And, that’s all — you can then play around with Fluent NHibernate and perform CRUD operations on your database as needed. Next, learn how to implement mappings using Fluent NHibernate.

Mapping Relations with Fluent NHibernate

In this section I explain how you can implement mappings using Fluent NHibernate.

One-to-One Mapping

Consider the following class, called Product.

 public class Product    {        public virtual Int32 ProductID { get; set; }                public virtual String Description { get; set; }      public virtual String CreatedBy { get; set; }        public virtual DateTime CreatedDate { get; set; }                public virtual String ModifiedBy { get; set; }        public virtual DateTime ModifiedDate { get; set; }        public virtual Int32 ProductTypeId { get; set; }        public virtual String Model { get; set; }    }

To create a one-to-one mapping for the above class, you need to create a class that extends the generic ClassMap class. Here is an example:

public class ProductMap : ClassMap    {        public ProductMap()        {            Table("Products");            Id(x => x.ProductID).GeneratedBy.Identity();            Map(x => x.Description);            Map(x => x.ModifiedBy);            Map(x => x.ModifiedDate);            Map(x => x.CreatedBy);            Map(x => x.CreatedDate);                      Map(x => x.ProductTypeId);            Map(x => x.Model);        }    }

One-to-Many Mapping

Consider the following two classes, User and Roles:

public class User{    virtual public int UserID { get; set; }    virtual public string UserName { get; set; }    virtual public string EmailAddress { get; set; }    virtual public string Password { get; set; }    virtual public Roles UserRoles {get; set;} }public class Roles{   public  Roles ()       {             UserList = new List();       }    virtual public int RoleID { get; set; }    virtual public string RoleName { get; set; }    virtual public string RoleXML { get; set; }    public IList UserList { get; protected set;}}

With this one-to-many mapping between user and roles, one user can have multiple roles. Here are the mapping classes to implement this.

public class UserMap : ClassMap    {        public UserMap()        {            Table("User");            Id(x => x.UserID).GeneratedBy.Identity();            Map(x => x.UserName);            Map(x => x.EmailAddress);            Map(x => x.Password);            References(x => x.Roles);        }    }

The RolesMap class maps the user’s roles as shown below:

public class RolesMap : ClassMap    {        public RolesMap()        {            Table("Roles");            Id(x => x.RoleID).GeneratedBy.Increment();            Map(x => x.RoleName);            Map(x => x.RoleXML);            HasMany(x => x.UserList)            .IsInverse()            .AsBag();        }    }

Many-to-Many Mapping

Using the User and Roles classes, the following example demonstrates how to implement many-to-many relationships.

public class User{    virtual public int UserID { get; set; }    virtual public string UserName { get; set; }    virtual public string EmailAddress { get; set; }    virtual public string Password { get; set; }    public virtual IList UserRoles { get; set; }}public class Roles{    virtual public int RoleID { get; set; }    virtual public string RoleName { get; set; }    virtual public string RoleXML { get; set; }    public virtual IList Users { get; set; }}

Here is how the UserMap class would look.

public class UserMap : ClassMap    {        public UserMap()        {            Table("User");            Id(x => x.UserID).GeneratedBy.Identity();            Map(x => x.UserName);            Map(x => x.EmailAddress);            Map(x => x.Password);            HasManyToMany(x => x.UserRoles).Table("RolesUser").ParentKeyColumn("UserID")                                         .ChildKeyColumn("RoleID");        }    }

The RolesMap class below implements a many-to-many relationship with Roles and User classes.

public class RolesMap : ClassMap    {        public RolesMap()        {            Table("Roles");            Id(x => x.RoleID).GeneratedBy.Increment();            Map(x => x.RoleName);            Map(x => x.RoleXML);            HasManyToMany(x => x.Users).Table("RolesUser")                                             .ParentKeyColumn("RoleID")                                             .ChildKeyColumn("UserID");        }    }

Notice the use of the HasManyToMany keyword while mapping the User and the Roles classes.

Summary

Fluent NHibernate offers a fluent API for mapping classes with NHibernate — sans the need for XML files. In this article you saw how to use Fluent NHibernate to implement various types of mappings, such as one-to-one, one-to-many and many-to-many.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may