In this article I will explain with an example, how to use Dependency Injection using Microsoft.Extensions.DependencyInjection in ASP.Net Core (.Net Core 7) MVC.
What is NHibernate?
NHibernate is an open source object-relational mapper for the .NET framework.
The primary feature is mapping from .NET classes to database tables.
It is based on Hibernate which is a popular Java object-relational mapper and it has a very mature and active code base.
It provides a framework for mapping an object-oriented model to a traditional relational database.
NHibernate supports a wide variety of different databases like SQL Server, Oracle, MySQL, PostgreSQL and etc.
Steps for implementing NHibernate
Following are the steps for implementing NHibernate in ASP.Net.
1. Install the
NHibernate package from
Nuget.
2. Create a class and define the properties.
3. Create a NHibernate mapping to load and save the business object.
4. Configure NHibernate to talk to the database.
Downloading NHibernate package
You will need to install the
NHibernate package from
Nuget.
Database
I have made use of the following table Customers with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Defining the Mapping
In order to enable mapping, you will need to add a new xml document by right clicking on the Solution Explorer and click on Add and then New Item.
Form the Add New Item dialog window, select XML File and give a suitable name i.e. Customer.hbm.xml and click on Add.
This is used by NHibernate to automatically recognize the file as a mapping file.
Note: The hbm is a part of the file name.
Once the xml file has been added, you need to set the Build Action with Embedded Resource.
For that, right click on the xml file and select Properties.
In the Properties dialog window, change the Build Action from Content to Embedded Resource and Copy to Output Directory from Do not copy to Copy always as shown below.
Inside the xml file you need to add hibernate-mapping root node to define mapping file.
Note: You need to define two attributes assembly and namespace of the root node.
Inside the hibernate-mapping node, define the class node and specify the following attributes.
name – Name of the class.
table – Name of the database table.
Inside the class node, define the property column according to the property as shown below.
Note: For more details on mapping declaration, please refer the documentation
here.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernate_Core"
namespace="NHibernate_Core.Models">
<class name="CustomerModel" table="Customers">
<id name="CustomerId" column="CustomerId">
<generator class="identity" />
</id>
<property name="Name" />
<property name="Country" />
</class>
</hibernate-mapping>
Now inside the hibernate.cfg.xml, you need to define the settings for connecting using data provider using hibernate-configuration.
The data provider has the following properties:
connection.provider – The type of a custom IConnectionProvider implementation.
dialect – The class name of a NHibernate Dialect.
connection.driver_class – The type of a custom IDriver, if using DriverConnectionProvider.
connection.connection_string – Connection string to use to obtain the connection.
show_sql – Write all SQL statements to console. Defaults to FALSE.
Note: For more details, please refer the documentation
here.
<configSections>
<section name=" hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect"> NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=.\SQL2022;Initial Catalog=AjaxSamples;User ID=sa;Password=pass@123;</property>
<property name="show_sql">true</property>
<mapping assembly="NHibernate_Core" />
</session-factory>
</hibernate-configuration>
Model
The Model class consists of following properties.
The class will contain properties with names similar to the Customers Table. This is necessary as it will be used to load the appropriate fields in appropriate properties i.e. CustomerId will be loaded in CustomerId property.
Note: The properties needs to be assign with the key word virtual. Because NHibernate is by default configured to use lazy load for all entities.
public class CustomerModel
{
public virtual int CustomerId{ get; set; }
public virtual string Name{ get; set; }
public virtual string Country{ get; set; }
}
Namespaces
You will need to import the following namespaces.
using NHibernate;
using NHibernate.Cfg;
Controller
The Controller consists of following Action method.
Action Method for handling GET operation
Inside this Action method, first the Configuration class object is created which is being configured using its Configure method.
Then, an instance of ISessionFactory interface is initiated where BuildSessionFactory method of Configuration class is called which basically gathers the meta-data.
Note: meta-data is nothing but contains information of assembly reference and other standaralized information such as type definition.
After that, ISession object is initialized and OpenSession method of ISessionFactory is called which is used to explicitly close and flush session object when it is done.
Transaction is initiated using BeginTransaction method of ISession interface.
A Generic List collection of CustomerModel class is created and using CreateCriteria method of ISession interface, the records are fetched from the database and the Commit method of ITransaction interface is called.
Finally, the Generic List collection of CustomerModel class is returned to the View.
public class HomeController : Controller
{
public IActionResult Index()
{
Configuration _configuration = new Configuration();
_configuration.Configure();
using (ISessionFactory _sessionFactory = _configuration.BuildSessionFactory())
{
using (NHibernate.ISession _session = _sessionFactory.OpenSession())
{
using (ITransaction tran = _session.BeginTransaction())
{
List<CustomerModel> customers = (List<CustomerModel>)_session.CreateCriteria<CustomerModel>().List<CustomerModel>();
tran.Commit();
return View(customers);
}
}
}
}
}
View
HTML Markup
Inside the View, an HTML Table is used. A FOR EACH loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using NHibernate_MVC.Models;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads