Using Fluent NHibernate for XML-Free Class Mapping

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.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists