AngularJS CRUD Operations With Web API 2 Using Nhibernate - Part One

Introduction

In this post, we will learn how to perform CRUD (Create, Read, Update, Delete) operations using Web API2 and NHibernate ORM Framework. Also, this article will give you a global vision of how we can use AngularJS Framework in a real application, by using some features like module, routing, service and controller. I hope you will like this.

Prerequisites

As I said earlier, to achieve our requirement, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.
In this part, we are going to-

  • Create our MVC application.
  • Configure NHibernate Framework to connect to the database.
  • Implement all HTTP Services needed.
So, let’s go.

SQL Database part

Here, find the scripts to create the database and table.

Create Database
  1. USE[master]    
  2. GO    
  3. /****** Object: Database [DbEmployee] Script Date: 9/20/2016 4:42:42 AM ******/    
  4. CREATE DATABASE[DbEmployee]    
  5. CONTAINMENT = NONE    
  6. ON PRIMARY    
  7.     (NNAME = N 'DbEmployee', FILENAME = N 'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee.mdf'SIZE = 3072 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)    
  8. LOG ON    
  9.     (NNAME = N 'DbEmployee_log', FILENAME = N 'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DbEmployee_log.ldf'SIZE = 1024 KB, MAXSIZE = 2048 GB, FILEGROWTH = 10 % )    
  10. GO    
  11. ALTER DATABASE[DbEmployee] SET COMPATIBILITY_LEVEL = 110    
  12. GO    
  13. IF(1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))    
  14. begin    
  15. EXEC[DbEmployee].[dbo].[sp_fulltext_database] @action = 'enable'    
  16. end    
  17. GO    
  18. ALTER DATABASE[DbEmployee] SET ANSI_NULL_DEFAULT OFF    
  19. GO    
  20. ALTER DATABASE[DbEmployee] SET ANSI_NULLS OFF    
  21. GO    
  22. ALTER DATABASE[DbEmployee] SET ANSI_PADDING OFF    
  23. GO    
  24. ALTER DATABASE[DbEmployee] SET ANSI_WARNINGS OFF    
  25. GO    
  26. ALTER DATABASE[DbEmployee] SET ARITHABORT OFF    
  27. GO    
  28. ALTER DATABASE[DbEmployee] SET AUTO_CLOSE OFF    
  29. GO    
  30. ALTER DATABASE[DbEmployee] SET AUTO_CREATE_STATISTICS ON    
  31. GO    
  32. ALTER DATABASE[DbEmployee] SET AUTO_SHRINK OFF    
  33. GO    
  34. ALTER DATABASE[DbEmployee] SET AUTO_UPDATE_STATISTICS ON    
  35. GO    
  36. ALTER DATABASE[DbEmployee] SET CURSOR_CLOSE_ON_COMMIT OFF    
  37. GO    
  38. ALTER DATABASE[DbEmployee] SET CURSOR_DEFAULT GLOBAL    
  39. GO    
  40. ALTER DATABASE[DbEmployee] SET CONCAT_NULL_YIELDS_NULL OFF    
  41. GO    
  42. ALTER DATABASE[DbEmployee] SET NUMERIC_ROUNDABORT OFF    
  43. GO    
  44. ALTER DATABASE[DbEmployee] SET QUOTED_IDENTIFIER OFF    
  45. GO    
  46. ALTER DATABASE[DbEmployee] SET RECURSIVE_TRIGGERS OFF    
  47. GO    
  48. ALTER DATABASE[DbEmployee] SET DISABLE_BROKER    
  49. GO    
  50. ALTER DATABASE[DbEmployee] SET AUTO_UPDATE_STATISTICS_ASYNC OFF    
  51. GO    
  52. ALTER DATABASE[DbEmployee] SET DATE_CORRELATION_OPTIMIZATION OFF    
  53. GO    
  54. ALTER DATABASE[DbEmployee] SET TRUSTWORTHY OFF    
  55. GO    
  56. ALTER DATABASE[DbEmployee] SET ALLOW_SNAPSHOT_ISOLATION OFF    
  57. GO    
  58. ALTER DATABASE[DbEmployee] SET PARAMETERIZATION SIMPLE    
  59. GO    
  60. ALTER DATABASE[DbEmployee] SET READ_COMMITTED_SNAPSHOT OFF    
  61. GO    
  62. ALTER DATABASE[DbEmployee] SET HONOR_BROKER_PRIORITY OFF    
  63. GO    
  64. ALTER DATABASE[DbEmployee] SET RECOVERY SIMPLE    
  65. GO    
  66. ALTER DATABASE[DbEmployee] SET MULTI_USER    
  67. GO    
  68. ALTER DATABASE[DbEmployee] SET PAGE_VERIFY CHECKSUM    
  69. GO    
  70. ALTER DATABASE[DbEmployee] SET DB_CHAINING OFF    
  71. GO    
  72. ALTER DATABASE[DbEmployee] SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF)    
  73. GO    
  74. ALTER DATABASE[DbEmployee] SET TARGET_RECOVERY_TIME = 0 SECONDS    
  75. GO    
  76. ALTER DATABASE[DbEmployee] SET READ_WRITE    
  77. GO    
Create Table
  1. USE[DbEmployee]    
  2. GO    
  3. /****** Object: Table [dbo].[EmployeeTable] Script Date: 9/20/2016 4:43:09 AM ******/    
  4. SET ANSI_NULLS ON    
  5. GO    
  6. SET QUOTED_IDENTIFIER ON    
  7. GO    
  8. SET ANSI_PADDING ON    
  9. GO    
  10. CREATE TABLE[dbo].[EmployeeTable](    
  11.     [EmployeeID][int] IDENTITY(1, 1) NOT NULL, [FirstName][varchar](50) NULL, [LastName][varchar](50) NULL, [Gender][varchar](50) NULL, [Designation][nchar](10) NULL, [Salary][intNULL, [City][varchar](50) NULL, [Country][varchar](50) NULL,    
  12.     CONSTRAINT[PK_EmployeeTable] PRIMARY KEY CLUSTERED(    
  13.         [EmployeeID] ASC    
  14.     ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON[PRIMARY]    
  15. ON[PRIMARY]    
  16. GO    
  17. SET ANSI_PADDING OFF    
  18. GO    
After creating the table, you can add some records, as shown below.

records

Create your MVC application

Open Visual Studio and select File >> New project. The "New Project" dialog box will pop up. Select ASP.NET Web Application (.NET Framework) >> name your project as CRUD_App >> click OK.

records

A new dialog box will pop up for selecting the template. We are going to choose Web API template and click OK.

Web API template

After creating our project, we are going to add NHibernate Framework.

Adding NHibernate Framework

First of all, in the Models folder, we will add our Employee Model, as shown below.

EmployeeModel.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace CRUD_App.Models {  
  6.     public class EmployeeModel {  
  7.         public virtual int ? EmployeeID {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public virtual string FirstName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public virtual string LastName {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public virtual string Gender {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public virtual string Designation {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public virtual int Salary {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public virtual string City {  
  32.             get;  
  33.             set;  
  34.         }  
  35.         public virtual string Country {  
  36.             get;  
  37.             set;  
  38.         }  
  39.     }  
  40. }  
In order to add NHibernate Framework, right click on References from Solution Explorer. Then, click on Manage NuGet Packages.

Framework

From NuGet Package Manager dialog box, type NHibernate in search text box. Select NHibernate as shown below, and click on Install button. After that, all the require dll references will be installed in our MVC application.

application MVC

Now, from Solution Explorer, add new folder which have DAL name. Inside it, we need to add two xml files as follows.

application MVC

For adding xml file, right click on DAL folder > Add > New Item and select XML File as shown below.

application MVC

Nh.configuration.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">  
  3.     <session-factory>  
  4.         <property name="connection.provider">  
  5.             NHibernate.Connection.DriverConnectionProvider  
  6.         </property>  
  7.         <property name="connection.driver_class">  
  8.             NHibernate.Driver.SqlClientDriver  
  9.         </property>  
  10.         <!-- Here, you need to specify connection String -->  
  11.         <property name="connection.connection_string">  
  12.             Data Source=.;Initial Catalog=DbEmployee;Integrated Security=True;  
  13.         </property>  
  14.         <property name="dialect">  
  15.             NHibernate.Dialect.MsSql2012Dialect  
  16.         </property>  
  17.     </session-factory>  
  18. </hibernate-configuration>  
Note

NHibernate ORM Framework can work with any databases, you need just make some settings like specifying provider, driver class and connection String.

Employee.mapping.xml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="CRUD_App" namespace="CRUD_App.Models">  
  3.     <class name="EmployeeModel" table="EmployeeTable" dynamic-update="true">  
  4.         <cache usage="read-write" />  
  5.         <id name="EmployeeID" column="EmployeeID" type="int">  
  6.             <generator class="native" />  
  7.         </id>  
  8.         <property name="FirstName" />  
  9.         <property name="LastName" />  
  10.         <property name="Gender" />  
  11.         <property name="Designation" />  
  12.         <property name="Salary" />  
  13.         <property name="City" />  
  14.         <property name="Country" />  
  15.     </class>  
  16. </hibernate-mapping>  
In this file, we are going to map our model class (Employee Model) with database table (EmployeeTable).

Open session for NHibernate

For opening session, we need add class file with static function. So, right click on Models folder > Add > Class.

OpenSessionNHibernate.cs

  1. using NHibernate;  
  2. using NHibernate.Cfg;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web;  
  7. namespace CRUD_App.Models {  
  8.     public class OpenSessionNHibernate {  
  9.         public static ISession OpenSession() {  
  10.             var configuration = new Configuration();  
  11.   
  12.             var configurationPath = HttpContext.Current.Server.MapPath(@ "~\DAL\nh.configuration.xml");  
  13.   
  14.             configuration.Configure(configurationPath);  
  15.   
  16.             var employeeConfigurationFile = HttpContext.Current.Server.MapPath(@ "~\DAL\Employee.mapping.xml");  
  17.   
  18.             configuration.AddFile(employeeConfigurationFile);  
  19.   
  20.             ISessionFactory sessionFactory = configuration.BuildSessionFactory();  
  21.   
  22.             return sessionFactory.OpenSession();  
  23.         }  
  24.     }  
  25. }  
Create a controller

Now, we are going to create a controller. Right click on the Controllers folder > Add > Controller> select Web API 2 Controller – Empty > click Add.

Controller

Enter Controller name (‘EmployeeController’).

Controller

EmployeeController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using CRUD_App.Models;  
  8. using NHibernate;  
  9. using NHibernate.Linq;  
  10. namespace CRUD_App.Controllers {  
  11.     public class EmployeeController: ApiController {  
  12.         //NHibernate Session  
  13.         ISession session = OpenSessionNHibernate.OpenSession();  
  14.         //Get All Employee  
  15.         public List < EmployeeModel > GetListEmployee() {  
  16.                 List < EmployeeModel > employee = session.Query < EmployeeModel > ().ToList();  
  17.                 return employee;  
  18.             }  
  19.             //Add New Employee  
  20.             [HttpPost]  
  21.         public HttpResponseMessage AddNewEmployee(EmployeeModel employee) {  
  22.                 try {  
  23.                     if (ModelState.IsValid) {  
  24.                         using(ITransaction transaction = session.BeginTransaction()) {  
  25.                             session.Save(employee);  
  26.                             transaction.Commit();  
  27.                         }  
  28.                         return Request.CreateResponse(HttpStatusCode.OK, "Success");  
  29.                     } else {  
  30.                         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error !");  
  31.                     }  
  32.                 } catch (Exception ex) {  
  33.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  34.                 }  
  35.             }  
  36.             //GetEmployeeData  
  37.             [HttpGet]  
  38.         public EmployeeModel DetailsEmployee(int id) {  
  39.                 var employee = session.Get < EmployeeModel > (id);  
  40.                 return employee;  
  41.             }  
  42.             //UpdateEmployee  
  43.             [HttpPut]  
  44.         public HttpResponseMessage UpdateEmployee(EmployeeModel employee) {  
  45.                 try {  
  46.                     if (ModelState.IsValid) {  
  47.                         var emp = session.Get < EmployeeModel > (employee.EmployeeID);  
  48.                         emp.FirstName = employee.FirstName;  
  49.                         emp.LastName = employee.LastName;  
  50.                         emp.Gender = employee.Gender;  
  51.                         emp.Designation = employee.Designation;  
  52.                         emp.Salary = employee.Salary;  
  53.                         emp.City = employee.City;  
  54.                         emp.Country = employee.Country;  
  55.                         using(ITransaction transaction = session.BeginTransaction()) {  
  56.                             session.Save(emp);  
  57.                             transaction.Commit();  
  58.                         }  
  59.                         return Request.CreateResponse(HttpStatusCode.OK, "Success");  
  60.                     } else {  
  61.                         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error !");  
  62.                     }  
  63.                 } catch (Exception ex) {  
  64.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  65.                 }  
  66.             }  
  67.             //Delete Employee  
  68.             [HttpDelete]  
  69.         public HttpResponseMessage DeleteEmployee(int id) {  
  70.             try {  
  71.                 var employee = session.Get < EmployeeModel > (id);  
  72.                 if (employee != null) {  
  73.                     using(ITransaction transaction = session.BeginTransaction()) {  
  74.                         session.Delete(employee);  
  75.                         transaction.Commit();  
  76.                     }  
  77.                     return Request.CreateResponse(HttpStatusCode.OK, "Success");  
  78.                 } else {  
  79.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Error !");  
  80.                 }  
  81.             } catch (Exception ex) {  
  82.   
  83.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  84.             }  
  85.         }  
  86.     }  
  87. }  
In the next part, we will learn how we can use Web API 2 with AngularJS Framework. That’s all. Please send your feedback and queries in comments box.


Similar Articles