Friday 29 December 2017

Fluent Nhibernet Step by Step Process for Begineers



Hello,

Please follow the steps below to create a employee registration form using the FluentNhibernate.


Step 1 : Add the Fluent NHibernate dll for the new empty  MVC project you have created.
           
              Using the Nuget Manager Console install the packages in the given order.If you have .net framework 4.5 or above you can install a higher version of DLLs than below and make sure you install all the dependencies as how I did below

  • Install-Package Iesi.Collections -Version 4.0.1.4000
  • Install-Package NHibernate -Version 4.0.3.4000
  • Install-Package FluentNHibernate -Version 2.0.1


Note : If you are unable to add them through the Packet manager make sure you install the below DLLs
  • FluentNHibernate - 1.3.0.717
  • Iesi.Collections - 1.0.1.0
  • NHibernate - 3.2.0.400

Step 2 : Make sure you have the below folders in the Visual Studio.Probably you will be adding the Mapping folder
















Step 3:

Add a controller in the contoller folder  with name EmployeeController and then add two class files in the models with the names as in below screen and a class file in Mapping  and view pages in them with the names as in below screen





























Step 4:
 Create the SQL script as shown below for the required database you wish to

CREATE TABLE [dbo].[Employee]
(
    [Id] INT NOT NULL PRIMARY KEY identity(1,1), 
    [FirstName] NVARCHAR(50) NULL, 
    [LastName] NVARCHAR(50) NULL, 
    [Designation] NVARCHAR(50) NULL
)

insert into [Employee] values('Raj','R','Program Analyst')
insert into [Employee] values('Maha','K','Trainee')
insert into [Employee] values('Rahul','N','Business Analyst')


Step 5:

Add the code to the class files you have created from the below source for Controller,Mapping,Model and Views

Controller:

EmployeeController.cs: 

using FluentNhibernateDemo.Models;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate.Linq;

namespace FluentNhibernateDemo.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                var employees = session.Query<Employee>().ToList();
                return View(employees);
            }
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(FormCollection employeeForm)
        {          
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    Employee empCreate = new Employee();
                    empCreate.Id = Convert.ToInt32(employeeForm["Id"]);
                    empCreate.FirstName = employeeForm["FirstName"];
                    empCreate.LastName = employeeForm["LastName"];
                    empCreate.Designation = employeeForm["Designation"];
                    session.Save(empCreate);
                    transaction.Commit();
                }
            }

            return RedirectToAction("Index");
        }
        public ActionResult Details(int id)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                Employee employees = session.Query<Employee>().Where(x=>x.Id== id).FirstOrDefault();
                return View(employees);
            }
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                Employee employees = session.Query<Employee>().Where(x => x.Id == id).FirstOrDefault();
                return View(employees);
            }
        }

        [HttpPost]
        public ActionResult Edit(FormCollection employeeForm)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    Employee empCreate = new Employee();
                    empCreate.Id = Convert.ToInt32(employeeForm["Id"]);
                    empCreate.FirstName = employeeForm["FirstName"];
                    empCreate.LastName = employeeForm["LastName"];
                    empCreate.Designation = employeeForm["Designation"];
                    session.Merge(empCreate);
                    transaction.Commit();
                }
            }

            return RedirectToAction("Index");
        }

        
        public ActionResult Delete(int id)
        {
            using (var session = NHibernateHelper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    Employee employees = session.Query<Employee>().Where(x => x.Id == id).FirstOrDefault();
                    session.Delete(employees);
                    transaction.Commit();
                }
            }

            return RedirectToAction("Index");
        }
    }
}

Mappings 

EmployeeMap.cs

using FluentNHibernate.Mapping;
using FluentNhibernateDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FluentNhibernateDemo.Mappings
{
    public class EmployeeMap : ClassMap<Employee>
    {
        public EmployeeMap()
        {
            Id(x => x.Id);
            Map(x => x.FirstName);
            Map(x => x.LastName);
            Map(x => x.Designation);
            Table("Employee");
        }
    }
}

Models

We need to add two files in model one is for model and other one is for Session processing using Nhibernate 

a)Employee.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FluentNhibernateDemo.Models
{
    public class Employee
    {
        public virtual int Id { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        public virtual string Designation { get; set; }
    }
}

b)NHibernateHelper.cs

using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FluentNhibernateDemo.Models
{
    public class NHibernateHelper
    {
         public static ISession OpenSession()
        {
            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(c => c.FromConnectionStringWithKey("StudentContext"))
                              .ShowSql()
                )
               .Mappings(m =>
                          m.FluentMappings
                              .AddFromAssemblyOf<Employee>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                                .Create(false, false))
                .BuildSessionFactory();
            return sessionFactory.OpenSession();
        }
    }
}

Views

a)Index.cshtml
@model IEnumerable<FluentNhibernateDemo.Models.Employee>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Designation)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Designation)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

</table>


b)Edit.cshtml
@model FluentNhibernateDemo.Models.Employee

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

        @Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Designation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Designation)
            @Html.ValidationMessageFor(model => model.Designation)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


c)Details.cshtml
@model FluentNhibernateDemo.Models.Employee

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.FirstName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.FirstName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.LastName)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.LastName)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Designation)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Designation)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

d)Create.cshtml
@model FluentNhibernateDemo.Models.Employee

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Designation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Designation)
            @Html.ValidationMessageFor(model => model.Designation)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Step 6:

a)Final Step is to add the connection string with the name we have provided in NHibernateHelper class
Just modify the below connection string and paste in your web.config

<connectionStrings>
    <add name="StudentContext" connectionString="server=USER-PC;database=MyDB;integrated security=SSPI"
         providerName="System.Data.SqlClient"/>

  </connectionStrings>

b)To launch your application change the controller name to "Employee"(You can find this under the solution folders -->App_Start-->Route.config.cs)


---------------------------  :-)  Thank You  :-) -----------------------------






No comments:

Post a Comment