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- USE[master]
- GO
- /****** Object: Database [DbEmployee] Script Date: 9/20/2016 4:42:42 AM ******/
- CREATE DATABASE[DbEmployee]
- CONTAINMENT = NONE
- ON PRIMARY
- (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)
- LOG ON
- (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 % )
- GO
- ALTER DATABASE[DbEmployee] SET COMPATIBILITY_LEVEL = 110
- GO
- IF(1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
- begin
- EXEC[DbEmployee].[dbo].[sp_fulltext_database] @action = 'enable'
- end
- GO
- ALTER DATABASE[DbEmployee] SET ANSI_NULL_DEFAULT OFF
- GO
- ALTER DATABASE[DbEmployee] SET ANSI_NULLS OFF
- GO
- ALTER DATABASE[DbEmployee] SET ANSI_PADDING OFF
- GO
- ALTER DATABASE[DbEmployee] SET ANSI_WARNINGS OFF
- GO
- ALTER DATABASE[DbEmployee] SET ARITHABORT OFF
- GO
- ALTER DATABASE[DbEmployee] SET AUTO_CLOSE OFF
- GO
- ALTER DATABASE[DbEmployee] SET AUTO_CREATE_STATISTICS ON
- GO
- ALTER DATABASE[DbEmployee] SET AUTO_SHRINK OFF
- GO
- ALTER DATABASE[DbEmployee] SET AUTO_UPDATE_STATISTICS ON
- GO
- ALTER DATABASE[DbEmployee] SET CURSOR_CLOSE_ON_COMMIT OFF
- GO
- ALTER DATABASE[DbEmployee] SET CURSOR_DEFAULT GLOBAL
- GO
- ALTER DATABASE[DbEmployee] SET CONCAT_NULL_YIELDS_NULL OFF
- GO
- ALTER DATABASE[DbEmployee] SET NUMERIC_ROUNDABORT OFF
- GO
- ALTER DATABASE[DbEmployee] SET QUOTED_IDENTIFIER OFF
- GO
- ALTER DATABASE[DbEmployee] SET RECURSIVE_TRIGGERS OFF
- GO
- ALTER DATABASE[DbEmployee] SET DISABLE_BROKER
- GO
- ALTER DATABASE[DbEmployee] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
- GO
- ALTER DATABASE[DbEmployee] SET DATE_CORRELATION_OPTIMIZATION OFF
- GO
- ALTER DATABASE[DbEmployee] SET TRUSTWORTHY OFF
- GO
- ALTER DATABASE[DbEmployee] SET ALLOW_SNAPSHOT_ISOLATION OFF
- GO
- ALTER DATABASE[DbEmployee] SET PARAMETERIZATION SIMPLE
- GO
- ALTER DATABASE[DbEmployee] SET READ_COMMITTED_SNAPSHOT OFF
- GO
- ALTER DATABASE[DbEmployee] SET HONOR_BROKER_PRIORITY OFF
- GO
- ALTER DATABASE[DbEmployee] SET RECOVERY SIMPLE
- GO
- ALTER DATABASE[DbEmployee] SET MULTI_USER
- GO
- ALTER DATABASE[DbEmployee] SET PAGE_VERIFY CHECKSUM
- GO
- ALTER DATABASE[DbEmployee] SET DB_CHAINING OFF
- GO
- ALTER DATABASE[DbEmployee] SET FILESTREAM(NON_TRANSACTED_ACCESS = OFF)
- GO
- ALTER DATABASE[DbEmployee] SET TARGET_RECOVERY_TIME = 0 SECONDS
- GO
- ALTER DATABASE[DbEmployee] SET READ_WRITE
- GO
Create Table- USE[DbEmployee]
- GO
- /****** Object: Table [dbo].[EmployeeTable] Script Date: 9/20/2016 4:43:09 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE[dbo].[EmployeeTable](
- [EmployeeID][int] IDENTITY(1, 1) NOT NULL, [FirstName][varchar](50) NULL, [LastName][varchar](50) NULL, [Gender][varchar](50) NULL, [Designation][nchar](10) NULL, [Salary][int] NULL, [City][varchar](50) NULL, [Country][varchar](50) NULL,
- CONSTRAINT[PK_EmployeeTable] PRIMARY KEY CLUSTERED(
- [EmployeeID] ASC
- ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
- ) ON[PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
After creating the table, you can add some records, as shown below.
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.
A new dialog box will pop up for selecting the template. We are going to choose Web API template and click OK.
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace CRUD_App.Models {
- public class EmployeeModel {
- public virtual int ? EmployeeID {
- get;
- set;
- }
- public virtual string FirstName {
- get;
- set;
- }
- public virtual string LastName {
- get;
- set;
- }
- public virtual string Gender {
- get;
- set;
- }
- public virtual string Designation {
- get;
- set;
- }
- public virtual int Salary {
- get;
- set;
- }
- public virtual string City {
- get;
- set;
- }
- public virtual string Country {
- get;
- set;
- }
- }
- }
In order to add NHibernate Framework, right click on References from Solution Explorer. Then, click on Manage NuGet Packages.
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.
Now, from Solution Explorer, add new folder which have DAL name. Inside it, we need to add two xml files as follows.
For adding xml file, right click on DAL folder > Add > New Item and select XML File as shown below.
Nh.configuration.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
- <session-factory>
- <property name="connection.provider">
- NHibernate.Connection.DriverConnectionProvider
- </property>
- <property name="connection.driver_class">
- NHibernate.Driver.SqlClientDriver
- </property>
-
- <property name="connection.connection_string">
- Data Source=.;Initial Catalog=DbEmployee;Integrated Security=True;
- </property>
- <property name="dialect">
- NHibernate.Dialect.MsSql2012Dialect
- </property>
- </session-factory>
- </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
- <?xml version="1.0" encoding="utf-8" ?>
- <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="CRUD_App" namespace="CRUD_App.Models">
- <class name="EmployeeModel" table="EmployeeTable" dynamic-update="true">
- <cache usage="read-write" />
- <id name="EmployeeID" column="EmployeeID" type="int">
- <generator class="native" />
- </id>
- <property name="FirstName" />
- <property name="LastName" />
- <property name="Gender" />
- <property name="Designation" />
- <property name="Salary" />
- <property name="City" />
- <property name="Country" />
- </class>
- </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
- using NHibernate;
- using NHibernate.Cfg;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace CRUD_App.Models {
- public class OpenSessionNHibernate {
- public static ISession OpenSession() {
- var configuration = new Configuration();
-
- var configurationPath = HttpContext.Current.Server.MapPath(@ "~\DAL\nh.configuration.xml");
-
- configuration.Configure(configurationPath);
-
- var employeeConfigurationFile = HttpContext.Current.Server.MapPath(@ "~\DAL\Employee.mapping.xml");
-
- configuration.AddFile(employeeConfigurationFile);
-
- ISessionFactory sessionFactory = configuration.BuildSessionFactory();
-
- return sessionFactory.OpenSession();
- }
- }
- }
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.
Enter Controller name (‘EmployeeController’).
EmployeeController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using CRUD_App.Models;
- using NHibernate;
- using NHibernate.Linq;
- namespace CRUD_App.Controllers {
- public class EmployeeController: ApiController {
- //NHibernate Session
- ISession session = OpenSessionNHibernate.OpenSession();
- //Get All Employee
- public List < EmployeeModel > GetListEmployee() {
- List < EmployeeModel > employee = session.Query < EmployeeModel > ().ToList();
- return employee;
- }
- //Add New Employee
- [HttpPost]
- public HttpResponseMessage AddNewEmployee(EmployeeModel employee) {
- try {
- if (ModelState.IsValid) {
- using(ITransaction transaction = session.BeginTransaction()) {
- session.Save(employee);
- transaction.Commit();
- }
- return Request.CreateResponse(HttpStatusCode.OK, "Success");
- } else {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error !");
- }
- } catch (Exception ex) {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
- //GetEmployeeData
- [HttpGet]
- public EmployeeModel DetailsEmployee(int id) {
- var employee = session.Get < EmployeeModel > (id);
- return employee;
- }
- //UpdateEmployee
- [HttpPut]
- public HttpResponseMessage UpdateEmployee(EmployeeModel employee) {
- try {
- if (ModelState.IsValid) {
- var emp = session.Get < EmployeeModel > (employee.EmployeeID);
- emp.FirstName = employee.FirstName;
- emp.LastName = employee.LastName;
- emp.Gender = employee.Gender;
- emp.Designation = employee.Designation;
- emp.Salary = employee.Salary;
- emp.City = employee.City;
- emp.Country = employee.Country;
- using(ITransaction transaction = session.BeginTransaction()) {
- session.Save(emp);
- transaction.Commit();
- }
- return Request.CreateResponse(HttpStatusCode.OK, "Success");
- } else {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error !");
- }
- } catch (Exception ex) {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
- //Delete Employee
- [HttpDelete]
- public HttpResponseMessage DeleteEmployee(int id) {
- try {
- var employee = session.Get < EmployeeModel > (id);
- if (employee != null) {
- using(ITransaction transaction = session.BeginTransaction()) {
- session.Delete(employee);
- transaction.Commit();
- }
- return Request.CreateResponse(HttpStatusCode.OK, "Success");
- } else {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Error !");
- }
- } catch (Exception ex) {
-
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
- }
- }
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.