NHibernate for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is NHibernate and why is it needed?

\n\n

NHibernate is a powerful and mature object-relational mapping (ORM) library for the .NET platform, written in C#. It is a port of the famous Java library Hibernate. NHibernate solves the fundamental problem of mismatch between the object-oriented data model in your C# application and the relational data model in the database (SQL Server, PostgreSQL, MySQL, Oracle, etc.).

\n\n

The main task of NHibernate is to automate the transformation of data between C# objects (POCO — Plain Old CLR Objects) and records in database tables. Instead of writing hundreds of lines of repetitive SQL code for CRUD operations (Create, Read, Update, Delete), you work with objects, and NHibernate handles the generation and execution of SQL queries.

\n\n

Why use NHibernate?

\n
    \n
  • Increased development productivity: You write less code, especially boilerplate code for working with ADO.NET.
  • \n
  • Reduced number of errors: SQL queries are generated automatically, reducing the risk of syntax errors and SQL injections (when used correctly).
  • \n
  • Database independence: You can change the DBMS by only modifying the connection string and NHibernate dialect, without rewriting business logic.
  • \n
  • Cache management: Built-in first and second level caching mechanisms significantly speed up application performance.
  • \n
  • Lazy Loading: Related data is loaded only when it is actually needed, saving resources.
  • \n
  • Powerful query language: HQL (Hibernate Query Language) and LINQ to NHibernate allow you to write type-safe queries.
  • \n
\n\n

Installing NHibernate

\n\n

NHibernate is distributed via NuGet — the package manager for .NET. Installation is very simple.

\n\n

Via Package Manager Console:

\n
Install-Package NHibernate
\n\n

Via .NET CLI (for .NET Core / .NET 5+ projects):

\n
dotnet add package NHibernate
\n\n

Additional packages (as needed):

\n
    \n
  • NHibernate.Caches.CoreMemoryCache — for second-level caching.
  • \n
  • System.Data.SqlClient or Microsoft.Data.SqlClient — for working with SQL Server.
  • \n
  • Npgsql — for working with PostgreSQL.
  • \n
  • MySql.Data — for working with MySQL.
  • \n
\n\n

After installation, you will need to configure the configuration (usually in app.config, web.config, or appsettings.json) or via Fluent configuration in code.

\n\n

Quick Start with Code Example

\n\n

Let's look at a simple example of working with NHibernate. Suppose we have a Products table in a SQL Server database.

\n\n

1. Create the entity class:

\n
public class Product\n{\n    public virtual int Id { get; set; }\n    public virtual string Name { get; set; }\n    public virtual decimal Price { get; set; }\n}
\n

Important: All properties must be virtual — this is a requirement of NHibernate for implementing proxy mechanisms (lazy loading, change tracking).

\n\n

2. Create the mapping file (Product.hbm.xml):

\n
<?xml version="1.0" encoding="utf-8" ?>\n<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"\n                   assembly="YourAssemblyName"\n                   namespace="YourNamespace">\n    <class name="Product" table="Products">\n        <id name="Id" column="ProductId">\n            <generator class="native" />\n        </id>\n        <property name="Name" column="Pro                    

Recommendations