NHibernate building an ASP. NET MVC Application

Source: Internet
Author: User
Tags actionlink

NHibernate building an ASP. NET MVC application what is NHibernate?

NHibernate is an object/relational database mapping tool for the. NET environment. The term object/relational database mapping (Object/relational mapping,orm) represents a technique used to map objects represented by object models to SQL-based relational model data structures.

NHibernate is a. Net-based object persistence class library for relational databases. NHibernate comes from a very good Java-based hibernate-relational persistence tool.

The goal of NHibernate is primarily for programming tasks related to data persistence, freeing developers from the writing of the original tedious SQL statements, freeing the developer to invest in the implementation of the business logic.

I do not like theoretical knowledge, or that sentence, practice the truth, I will be the most intuitive form to express. Let's start by building our NHibernate application.

Development environment: Win7, VS2012, Sqlserver2008

Building projects

I use the ASP. NET MVC Project

And then create a new 3 class library project in turn, shop.domain,shop.data,shop.business

The end result is as follows:

Project Schema Description

Adopt a traditional three-tier architecture

Shop.domain: Data entity and database mapping file. Others call it the domain layer.

Shop.data: Data layer, the operation of database and NHibernate auxiliary class. Referencing Iesi.collections.dll,nhibernate.dll and class libraries Shop.domain

Shop.business: Business logic class. Referencing the class library project Shop.domain, Shop.data

Shop.website: Test Project. You need to reference Iesi.collections.dll,nhibernate.dll and class library project Shop.domain, shop.business

Download NHibernate

After the installation is complete, the following references are added automatically:

Database design

For the sake of convenience, the database, I directly use Northwnd.mdf,: Http://files.cnblogs.com/files/jiekzou/northwnd.zip, Database--Additional

For descriptions of Northwind tables and fields, see: http://www.cnblogs.com/pnljs/archive/2012/04/26/2471046.html

NHibernate Database Configuration

Open this project Solution folder location: E:\WorkSpace\Study\Webs\MVC\Shop, you will find a Packages folder, open this Packages folder,

You will see a nhibernate.4.0.3.4000 folder that opens as:

The SQL Server2008 is used here, So we use the MSSQL.cfg.xml file, copy this file to the Shop.website application root directory, and then rename it to Hibernate.cfg.xml., modify the Hibernate.cfg.xml

Note that you need to modify the instance name of your database and add the mapping node and other settings that you can add as needed.

The changes are as follows (I have added a comment to the configuration file):

<?xml version= "1.0" encoding= "Utf-8"?><!--This template is written to work with NHibernate.Test.Copy the TEMPLA Te to your Nhibernate.test project folder and rename it in Hibernate.cfg.xml and change itfor your own use before compile   Tests in visualstudio.--><!--the "the System.Data.dll provider for SQL Server-->

Finally, remember to modify the properties of the Hibernate.cfg.xml file,

Nhibernatehelper Auxiliary class

Here you write a simple helper class nhibernatehelper, which is used to create isessionfactory and configure Isessionfactory, and to open a new ISession method. Create a new class Nhibernatehelper under the Shop.data project with the following code:

Using nhibernate;using nhibernate.cfg;using system;using system.collections.generic;using System.Linq;using System.text;using System.Threading.Tasks;
namespace shop.data{public class Nhibernatehelper { private isessionfactory _sessionfactory; Public Nhibernatehelper () { //create isessionfactory _sessionfactory = Getsessionfactory (); } <summary>//Create Isessionfactory//</summary>// <returns></returns> Public isessionfactory getsessionfactory () { //configure Isessionfactory return (new Configuration ()). Configure (). Buildsessionfactory (); } <summary>//Open ISession//</summary>// <returns></returns> Public ISession getsession () { return _sessionfactory.opensession ();}} }
Persistence class
Create a persisted class customers for the customer entity. Create a new folder in Project Shop.domain entities, and then create a new class customers, here in order to be lazy, I use the dynamic Soft tool generated code as follows:
Note: NHibernate uses the proxy feature by default, requiring that the persisted class is not sealed and that its public methods, properties, and events are declared as virtual. In this case, the field in the class is set to virtual, otherwise an exception of type "Nhibernate.invalidproxytypeexception" occurs in Shop.Data.dll, but is not processed in user code
public class Customers {#region Model private string _customerid;        private string _CompanyName;        private string _contactname;        private string _contacttitle;        private string _address;        private string _city;        private string _region;        private string _postalcode;        private string _country;        private string _phone; private string _fax;
<summary>///Customer ID PRIMARY key///</summary> public virtual string CustomerID {set {_customerid = value;} get {return _customerid;} }///<summary>////</summary> public virtual string CompanyName { set {_companyname = value;} get {return _companyname;} }///<summary>//Customer name///</summary> public virtual string ContactName {set {_contactname = value;} get {return _contactname;} }///<summary>//Customer title///</summary> public virtual string ContactTitle {set {_contacttitle = value;} get {return _contacttitle;} }///<summary>///Contact address//</summary> public virtual string Address { set {_address = VAlue; } get {return _address;} }///<summary>//city///</summary> public virtual string Cities { set {_city = value;} get {return _city;} }///<summary>///</summary> public virtual string Region { set {_region = value;} get {return _region;} }///<summary>/////</summary> public virtual string PostalCode { set {_postalcode = value;} get {return _postalcode;} }//<summary>//nationality///</summary> public virtual string Country { set {_country = value;} get {return _country;} }//<summary>///Phone//</summary> public virtual string Phone { set {_phone = value;} get {return _phone;} }//<summary>//Fax//</summary> public virtual string Fax { set {_fax = value;} get {return _fax;} } #endregion Model}
writing a mapping file

The ability to write NHibernate configuration file smart hints. Just find the configuration.xsd and nhibernate-mapping.xsd two files in the downloaded nhibernate and copy them to the VS installation directory, such as D:\Program files (x86) \microsoft Visual Studio 11.0\xml\schemas directory.

At this point, you have smart hints in the NHibernate configuration file.

How does NHibernate know the correspondence between persisted classes and database tables? This is done through the mapping file, which contains the metadata required for the object/relationship mapping. The metadata contains the declaration of the persisted class and the mapping of the property to the database. The mapping file tells NHibernate which table in the database it should access and which fields in the table are used.

Then we write the Customers persistence class mapping file, note that the map file ends with. hbm.xml. such as Customers.hbm.xml

I also use the dynamic Code generation tool to generate the mapping file, as follows:

<?xml version= "1.0" encoding= "Utf-8"? >

Finally, remember to set the properties for this mapping file

To add a data access Layer class CustomersData.cs:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using nhibernate;using nhibernate.linq;using nhibernate.cfg;using system.linq.expressions;using Shop.domain.entities;namespace shop.data{public class CustomersData {
<summary>
Get a collection of customer information based on conditions
</summary>
<param name= "where" > Conditions </param>
<returns> Customer Information Collection </returns>
Public ilist<customers> getcustomerlist (Expression<func<customers, bool>> where)
{
Try
{
Nhibernatehelper nhibernatehelper = new Nhibernatehelper ();
ISession session = Nhibernatehelper.getsession ();
return session. Query<customers> (). Select (x=>new Customers {contactname=x.contactname,city=x.city,address=x.address,phone=x.phone,companyname=x. Companyname,country=x.country}). where (where). ToList ();
}
catch (Exception ex)
{
Throw ex;
}
}
}
}

Add the business logic Layer class CustomersBusiness.cs:

Using system;using system.collections.generic;using system.linq;using system.linq.expressions;using System.Text; Using system.threading.tasks;using shop.data;using shop.domain.entities;namespace shop.business{public class        customersbusiness {private CustomersData _customersdata;        Public customersbusiness () {_customersdata = new customersdata (); }
<summary>
Get a collection of customer information based on conditions
</summary>
<param name= "where" > Conditions </param>
<returns> Customer Information Collection </returns>
Public ilist<customers> getcustomerlist (Expression<func<customers, bool>> where)
{
Return _customersdata.getcustomerlist (where);
}
}
}

To add a controller:

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;using shop.business;using shop.domain.entities;namespace shop.controllers{Public    class Customerscontroller: Controller    {        customersbusiness customersbusiness = new customersbusiness ();        //GET:/customer/public        actionresult Index ()        {            var result = Customersbusiness.getcustomerlist (c = > 1 = = 1);            return View (result);        
}
}

Add View index:

@model ienumerable<shop.domain.entities.customers>@{viewbag.title = "Index";}        

Run the program:

Cold a week has not been good, people very uncomfortable, poor I still work beside the computer, today, for the moment to write here, blogging is really time-consuming work.

NHibernate building an ASP. NET MVC Application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.