Wednesday, December 3, 2014

Fluent nhibernate MVC Sample

This article describing the how to implement the Fluent nhibernate. What first you have to know what is fluent nhibernate in .net?
What is NHibernate and fluent nhibernate in .net?
First you have to know about NHibernate. it is an object-relational mapping (ORM) solution for the Microsoft .NET platform. It provides a framework for mapping an object-oriented domain model to a traditional relational database.
Why would you need it?
Because it can save you from writing a lot of tedious ADO.NET code. Essentially it enhances developer productivity when developing CRUD applications, that is, applications whose main purpose is to Create, Read, Update, and Delete data in a database. NHibernate is open source, and you need to realize that you are making your application dependent on third party libraries, whose long term goals may diverge from yours.
In NHibernate we need to create mapping purely xml based. We need to create xml  mapping  to map the table where as  In Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
So here is basic step to learn fluent MVC
1) First create database and table in sql server 2008 (dbtesting) and table employee
CREATE TABLE [dbo].[Employee] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (256) NULL,
    [Description] NVARCHAR (256) NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([Id] ASC)
);

2) Visual studio express 2013 create new project and add a new web application project with ASP.NET MVC.  So once you are done with creating project. So you need to add fluent nhibernate library from nuget. So   go to visual studio 2013 tool->library package Manger. When you click on library package manger then package manger console open. Then type command
install-package fluentnhibernate
When you run this command .so the reference is added in your application. So you are done with this. Now to move on next step
3) So right click on Model folder and add new class employee.cs. Here is code
    public class Employee
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Description { get; set; }

    }
Once you have created the employee class so you need to map the class. So next stuff to map the class to database table.  So add new class employeemap.cs in model folder and it has following code is given below

public class EmployeeMap : ClassMap<Employee>//here is map class to database table
    {
        public EmployeeMap()
        {
            Id(x => x.Id);
            Map(x => x.Name);
            Map(x => x.Description);
            Table("Employee");
        }
    }
Once you have done with this stuff now we have move forward to implement the generic repository system

So I have added the generic interface “IRepository” in model folder and it has following code





public interface IRepository<T>
    {
        void Save(T entity);
        void Update(T entity);
        void Delete(T entity);
        T GetById(int id);
        IList<T> GetAll();
    }





You have see above it contain curd operation method.

So next step create sql server connection so added new class “NHibernateHelper.cs” and it has following code
 

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;


 
public class NHibernateHelper
    {
        /// <summary>
        /// create connection to execute database queries
        /// </summary>
        /// <returns></returns>
        public static ISession OpenSession()
        {
            ISessionFactory sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(@"Data Source=MOHITANILK;Initial Catalog=dbtesting;Integrated Security=True")
                              .ShowSql()
                )
               .Mappings(m =>
                          m.FluentMappings
                              .AddFromAssemblyOf<Employee>())//here mapping with databse
                .ExposeConfiguration(cfg => new SchemaExport(cfg)
                    .Create(false, false))
                .BuildSessionFactory();
            return sessionFactory.OpenSession();
        }
    }


You are done with this. Now you add new class employeerepository and it has following code

using NHibernate;
using NHibernate.Criterion;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication12.Models
{
    public class EmployeeRepository : IRepository<Employee>
    {

        /// <summary>
        /// Here is curd operation help to maintain clear code in controller
        /// </summary>
        /// <param name="entity"></param>
        public void Save(Employee entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(entity);
                    transaction.Commit();
                }
            }
        }

        public void Update(Employee entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Update(entity);
                   transaction.Commit();
                }
            }
        }

        public void Delete(Employee entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(entity);
                    transaction.Commit();
                }
            }
        }

        public Employee GetById(int id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.CreateCriteria<Employee>().Add(
                  Restrictions.Eq("Id", id)).UniqueResult<Employee>();
        }

        public IList<Employee> GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(Employee));

                return criteria.List<Employee>();
            }
        }
    }
}

So here is completed the core concept. now In controller how to called these method. in  my application  I have created the following index method and view to get all employee  here is code given below
Controller
public class HomeController : Controller
    {
        private IRepository<Employee> _employeeRepository;
        public HomeController()
        {
            _employeeRepository = new EmployeeRepository();
        }

        public ActionResult Index()
        {

            return View(_employeeRepository.GetAll());

        }
}

View
@model List<WebApplication12.Models.Employee> //webapplication12 its my application name

@{
    ViewBag.Title = "Home Page";
}


<table  class="table-bordered">
    <thead>

      <th> Name</th>
        <th> Descrption</th>
        <th> action</th>
    </thead>
    <tbody>
        @foreach (var emp in Model)
    {

            <tr>
                <td>@emp.Name</td>
                <td>@emp.Description</td>
                <td><a href="edit/@emp">Edit</a><td>
            </tr>

    }
    </tbody>
</table>
   Here is display the list of employee. Next stuff create you  from add new employee so go to   controller add  new method

Controller
   public ActionResult AddNewEmployee()
        {
            return View(new Employee());
        }

        [HttpPost]
        public ActionResult AddNewEmployee(Employee emp)
        {
            _employeeRepository.Save(emp);
            return RedirectToAction("Index");
        }

Add new strongly employee type view “” right click on AddNewEmployee method in controller as shown in figure
view
Add caption

Then it has following view
@model WebApplication12.Models.Employee

@{
    ViewBag.Title = "AddNewEmployee";
}

<h2>View1</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Description)
                @Html.ValidationMessageFor(model => model.Description)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
   </div>
}

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
  When  you run this  it has following output.

I have already created the method in controller to submit the from  as given below

        [HttpPost]
        public ActionResult AddNewEmployee(Employee emp)
        {
            _employeeRepository.Save(emp);
            return RedirectToAction("Index");
        }


No comments:

Post a Comment

http://blogsiteslist.com