Nhibernate C#

Introduction:

NHibernate serves as an Object-Relational Mapping (ORM) tool tailored for the .NET ecosystem, empowering programmers to link domain entities with a relational database. Derived from the Hibernate ORM framework in Java, NHibernate extends analogous capabilities to .NET developers. This guide delves into NHibernate's fundamentals and its application in conjunction with C#.

What is NHibernate?

NHibernate serves as an object-relational mapping (ORM) framework enabling developers to interact with a domain model using objects to encapsulate data instead of relying on SQL queries. NHibernate handles the translation between objects and the underlying database, freeing developers to concentrate on the core business logic of their applications.

NHibernate Architecture:

NHibernate relies on the ADO.NET infrastructure for database connectivity at a low level. To set up database connections, mappings, and various configurations, NHibernate employs a series of configuration files. These files are essential for defining database dialects, connection strings, and additional settings.

NHibernate provides a rich set of features including:

  • Automatic generation of SQL statements for database operations.
  • Support for transactions and concurrency control.
  • Lazy loading of objects to improve performance.
  • Support for caching to reduce database access.
  • Support for mapping inheritance hierarchies to database tables.

The fundamental elements of NHibernate Architecture consist of:

  1. SessionFactory:

It serves as the starting point for NHibernate, tasked with generating Session instances. This object is designed to be safe for concurrent use and is instantiated just once when the application begins.

  1. Session:

It serves as a lightweight entity employed for communication with the database. The Session object symbolizes a singular task, defined as a collection of operations that should be carried out in unison.

  1. Setup:

It is employed to set up NHibernate during the startup of the application. The configuration instance is utilized to define the connection string, database dialect, mapping files, and additional configurations.

  1. Specifying Mapping files:

NHibernate utilizes mapping files to establish a connection between object-oriented code and relational databases. These files define the mapping of each object and its attributes to the corresponding tables and columns in the database.

How does NHibernate Work?

NHibernate utilizes mapping files to establish the connection between the domain model and the database. These files outline the correspondence between the properties of domain objects and the structure of the database. NHibernate offers support for two varieties of mapping files:

XML-based mapping documents, which are specified using an XML structure.

Fluent Mapping involves employing C# code to establish the connections between domain entities and the database.

Here is an illustration of how NHibernate mapping operates. Assume we possess a Customer class containing the subsequent attributes:

C# Code:

Example

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string Email { get; set; }
}

We have the option to utilize mapping files to specify the connection between this class and the database. Below is a sample of an XML-driven mapping file for the Customer class:

XML Code:

Example

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="MyProject"
                   namespace="MyProject.Models">
  <class name="Customer" table="Customers">
    <id name="Id" column="CustomerId">
      <generator class="identity" />
    </id>
    <property name="FirstName" column="FirstName" />
    <property name="LastName" column="LastName" />
    <property name="Email" column="Email" />
  </class>
</hibernate-mapping>

This mapping configuration file establishes the connection between the Customer class and the Customers table within the database. It outlines that the Id attribute serves as the primary key within the table, while the FirstName, LastName, and Email attributes are linked to corresponding columns in the database bearing the same names.

NHibernate also provides support for Fluent Mapping, enabling developers to specify the relationship between domain entities and the database through C# code. Below is a demonstration illustrating how to configure the mapping for the Customer class using Fluent Mapping:

C# Code:

Example

public class CustomerMap : ClassMap<Customer>
{
    public CustomerMap()
    {
        Table("Customers");
        Id(x => x.Id, "CustomerId").GeneratedBy.Identity();
        Map(x => x.FirstName).Column("FirstName");
        Map(x => x.LastName).Column("LastName");
        Map(x => x.Email).Column("Email");
    }
}

This Fluent Mapping code establishes an equivalent mapping to the XML-based mapping file. It declares that the Customer class is associated with the Customers table in the database and that the attributes are linked to the columns bearing identical names.

NHibernate also offers a session entity that oversees the connection between the domain entities and the database. This session entity handles the creation, retrieval, modification, and removal of domain entities, as well as oversees transactions and concurrency. The session entity is lightweight and intended to have a brief lifespan. It should be instantiated when required and promptly terminated once the tasks are completed.

Input Required

This code uses input(). Please provide values below: