轉自:http://www.dotnetjalps.com/2013/09/asp-net-mvc-nhibernate-crud-getting-started.html
In this post we are going to learn how we can use NHibernate in ASP.NET MVC application.
What is NHibernate:
ORMs(Object Relational Mapper) are quite popular this days. ORM is a mechanism to map database entities to Class entity objects without writing a code for fetching data and write some SQL queries. It automatically generates SQL Query for us and fetch data behalf on us.
NHibernate is also a kind of Object Relational Mapper which is a port of popular Java ORM Hibernate. It provides a framework for mapping an domain model classes to a traditional relational databases. Its give us freedom of writing repetitive ADO.NET code as this will be act as our database layer. Let’s get started with NHibernate.
How to download:
There are two ways you can download this ORM. From nuget package and from the source forge site. Nuget - http://www.nuget.org/packages/NHibernate/ Source Forge-http://sourceforge.net/projects/nhibernate/ Creating a table for CRUD:
I am going to use SQL Server 2012 express edition as a database. Following is a table with four fields Id, First Name, Last name, Designation.
Creating ASP.NET MVC project for NHibernate:
Let’s create a ASP.NET MVC project for NHibernate via click on File-> New Project –> ASP.NET MVC 4 web application.
Installing NuGet package for NHibernate:
I have installed nuget package from Package Manager console via following Command.
It will install like following.
NHibertnate configuration file:
Nhibernate needs one configuration file for setting database connection and other details. You need to create a file with ‘hibernate.cfg.xml’ in model Nhibernate folder of your application with following details.
| <? xml version = "1.0" encoding = "utf-8" ?> < hibernate-configuration xmlns = "urn:nhibernate-configuration-2.2" > < session-factory > < property name = "connection.provider" > |