CRUD Operations In .Net Core Using NHibernet

In this article, we’ll learn how to perform CRUD operations with .NET Core 5.0 and Visual Studio 2019. We will use an NHibernet to perform CRUD operations.

What is NHibernate?

  • NHibernate is an open-source ORM(Object-Relational Mapping) framework.
  • Designed to serve as a persistence layer exclusively for the .Net framework based on ORM Technique.
  • tool that makes a “virtual representation” of database objects inside the code. Used to solve the problem of impedance discrepancy between class and relational databases and tables.

Create a new project

Open VS 2019, we need to click on the “Create a new project” box.

Put a suitable name and select the location where you want to create this project. Again, click the “Create” button.

After that, you have to select the .net core Target Framework 5.0

Install NuGet packages.

We need to install the NHibernate and System.Data.SQLite

Create Mapper Class and Interface

Now, create two folders –
  1. Helper
  2. Mapper

In the Helper folder, add a new interface namely “NHibernateExtensions” and copy the below code and paste it into that class.

using NHibernate.Cfg;
using NHibernate;
using NHibernate.Dialect;
using NHibernate.Mapping.ByCode;

namespace CrudNHibernate.NewFolder
{
    public static class NHibernateExtensions
    {
        public static ISession AddNHibernate()
        {
            try
            {
                var mapper = new ModelMapper();
                mapper.AddMappings(typeof(NHibernateExtensions).Assembly.ExportedTypes);
                var entityMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                var configuration = new Configuration();
                configuration.DataBaseIntegration(c =>
                {
                    c.Dialect<MsSql2012Dialect>();
                    c.ConnectionString = ""; // Add you database connection string 
                    c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                    c.SchemaAction = SchemaAutoAction.Update;
                    c.LogFormattedSql = true;
                    c.LogSqlInConsole = true;
                });
                configuration.AddMapping(entityMapping);
                var sessionFactory = configuration.BuildSessionFactory();
                return sessionFactory.OpenSession();
            }
            catch (System.Exception ex)
            {

                throw;
            }
        }
    }
}

In the Mapper folder, add a new class namely “UserMap” copy the below code and paste it into that class.

using CrudNHibernate.Models.Entities;
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;

namespace CrudNHibernate.Mapping
{
    public class UserMap : ClassMapping<UserMaster>
    {
        public UserMap()
        {
            Table("UserMaster");
            Id(i => i.Id, Map => Map.Generator(Generators.Identity));
            Property(x => x.Name);
            Property(x => x.Class);
            Property(x => x.Gender);
        }
    }
}

In the Models folder, add a new class namely “UserMaster” copy the below code and paste it into that class.

namespace CrudNHibernate.Models
{
    public class UserMaster
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual int Class { get; set; }
        public virtual string Gender { get; set; }
    }
}

Add Controller

In the Controller folder, add a new class namely “UserController” copy the below code and paste it into that class.

using System;
using NHibernate;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CrudNHibernate.Models;
using CrudNHibernate.NewFolder;

namespace CrudNHibernate.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        #region Get users list
        [HttpGet]
        [Route("getUsers")]
        public IActionResult GetUsers()
        {
            try
            {
                ISession session = NHibernateExtensions.AddNHibernate();
                var users = session.Query<UserMaster>().ToList();
                return Ok(users);
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }
        #endregion

        #region addUser
        [HttpPost]
        [Route("addUser")]
        public IActionResult AddUser(UserMaster userMaster)
        {
            try
            {
                ISession session = NHibernateExtensions.AddNHibernate();
                ITransaction transaction = session.BeginTransaction();
                session.Save(userMaster);
                transaction.Commit();
                return Ok("User add successfully.");
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }
        #endregion

        #region Edit user
        [HttpPost]
        [Route("editUser")]
        public IActionResult EditUser(UserMaster userMaster)
        {
            try
            {
                ISession session = NHibernateExtensions.AddNHibernate();
                var userUpdate = session.Get<UserMaster>(userMaster.Id);
                if (userUpdate != null)
                {
                    userUpdate.Name = userMaster.Name;
                    userUpdate.Class = userMaster.Class;
                    userUpdate.Gender = userMaster.Gender;
                    ITransaction transaction = session.BeginTransaction();
                    session.Save(userUpdate);
                    transaction.Commit();
                    return Ok("User Edit successfully.");
                }
                else
                {
                    return Ok("404 user not found.");
                }
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }
        #endregion

        #region Delete user
        [HttpDelete]
        [Route("deleteUser")]
        public IActionResult DeleteUser(int id)
        {
            try
            {
                ISession session = NHibernateExtensions.AddNHibernate();
                var userData = session.Get<UserMaster>(id);
                if (userData != null)
                {
                    ITransaction transaction = session.BeginTransaction();
                    session.Delete(userData);
                    transaction.Commit();
                    return Ok("User remove successfully.");
                }
                else
                {
                    return Ok("404 User not found.");
                }
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }
        #endregion

        #region Get particular user
        [HttpGet]
        [Route("getUser")]
        public IActionResult GetUser(int id)
        {
            try
            {
                ISession session = NHibernateExtensions.AddNHibernate();
                var userData = session.Get<UserMaster>(id);
                if (userData != null)
                    return Ok(userData);
                else
                    return Ok("404 User not found");
            }
            catch (Exception ex)
            {
                return Ok(ex);
            }
        }
        #endregion
    }
}

Summary

Here, we created a simple application that uses the NHibernate, Core 5.0 preview, SQL Server, and Visual Studio 2019 to perform CRUD operations. You can leave the feedback/comments/questions about this article below.

Also check, What Is NHibernate?

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories