ASP.NET MVC4中使用NHibernate


1:下載安裝NHibernate

打開 VS 2012新建一個 MVC4項目. 在項目名稱上右擊選擇Manage NuGet Packages。你會看見 Manage Nuget Packages 頁面. 在搜索框輸入‘NHibernate’ 可以得到以下結果:

選擇第一個並安裝,安裝完成后會引入以下兩個.DLL文件

  • NHibernate

  • Lesi.Collections

 

2:編寫Model層,你需要決定模型中的對象它們之間的關系現在來定義一個應用程序,用於維護員工記錄(很簡單但你可以擴展的讓我們添加新的類模型。如下所示

 1 public class EmployeeInfo 
 2 { 
 3 int _EmpNo; 
 4 public virtual int EmpNo 
 5 { 
 6   get { return _EmpNo; } 
 7   set { _EmpNo = value; } 
 8 } 
 9 string _EmpName; 
10 public virtual string EmpName 
11 { 
12   get { return _EmpName; } 
13   set { _EmpName = value; } 
14 } 
15 int _Salary;
16 public virtual int Salary 
17 { 
18   get { return _Salary; } 
19   set { _Salary = value; } 
20 } 
21 string _DeptName;
22 public virtual string DeptName 
23 { 
24   get { return _DeptName; } 
25   set { _DeptName = value; } 
26 } 
27 string _Designation;
28 public virtual string Designation 
29 { 
30   get { return _Designation; } 
31   set { _Designation = value; } 
32 } 
33 } 
View Code

包含屬性employeeinfo這些屬性將被用來與表的列映射這些屬性必須被定義為虛擬

 

3:一旦映射模型類准備好了,現在就可以建數據庫保存數據。對於這個簡單的應用程序,我們將使用一個名為Company的SQL數據庫。表的名稱是employeeinfo,創建如下所示:

 1 USE [Company] 
 2 GO 
 3 /****** Object:  Table [dbo].[EmployeeInfo]    Script Date: 1/17/2013 11:22:12 AM ******/ 
 4 SET ANSI_NULLS ON 
 5 GO 
 6 SET QUOTED_IDENTIFIER ON 
 7 GO 
 8 SET ANSI_PADDING ON 
 9 GO 
10 CREATE TABLE [dbo].[EmployeeInfo]( 
11     [EmpNo] [int] IDENTITY(1,1) NOT NULL, 
12     [EmpName] [varchar](50) NOT NULL, 
13     [Salary] [decimal](18, 0) NOT NULL, 
14     [DeptName] [varchar](50) NOT NULL, 
15     [Designation] [varchar](50) NOT NULL, 
16 CONSTRAINT [PK_EmployeeInfo] PRIMARY KEY CLUSTERED 
17 ( 
18     [EmpNo] ASC 
19 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
20 ) ON [PRIMARY] 
21 GO 
22 SET ANSI_PADDING OFF 
23 GO 
View Code

 

4:設置映射employeeinfo.HBM.XML

在Models中建立NHibernate 文件夾,在NHibernate下建立Configuration 、Mappings兩個文件夾

映射文件的命名規則默認是< modelName >.hbm.xml,在我們的案例中,它取名為employeeinfo.HBM.XML,保存在Models\Mappings,我們需要在項目中將XML文件屬性改為嵌入的資源的“。這個文件映射模型類與數據庫表列的約束的主鍵,數據類型等文件,如下所示:

 1 <?xml version="1.0" encoding="utf-8" ?> 
 2 <hibernate-mapping 
 3 xmlns="urn:nhibernate-mapping-2.2" 
 4 assembly="MVC4_Using_NHB" 
 5 namespace="MVC4_Using_NHB" 
 6 auto-import="true"> 
 7 <class name="MVC4_Using_NHB.Models.EmployeeInfo,MVC4_Using_NHB"> 
 8   <id name="EmpNo" access="property" column="EmpNo" type="Int32"> 
 9    <generator class="native"></generator> 
10   </id> 
11   <property name="EmpName" access="property" 
12    column="EmpName" type="String"></property> 
13   <property name="Salary" access="property" 
14    column="Salary" type="Int32"></property> 
15   <property name="DeptName" access="property" 
16    column="DeptName" type="String"></property> 
17   <property name="Designation" access="property" 
18    column="Designation" type="String"></property> 
19   </class> 
20 </hibernate-mapping> 
View Code

上述XML文件是employeeinfo類和屬性之間的映射的列。

注:默認情況下沒有智能代碼提示,可以實現添加nhibernate-configuration.xsd和nhibernate-mapping.xsd文件到VS的以下路徑:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\Xml\Schemas,就會有代碼提示。

 

5:一旦定義了映射,就可以定義應用程序的NHibernate配置。這提供了連接數據庫信息,連接字符串,用於連接映射文件。在項目中Models\Configuration文件夾建一個新的XML文件;該文件的名稱是‘hibernate.CFG.XML的。在添加以下配置:

 1 <?xml version="1.0" encoding="utf-8" ?> 
 2 <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> 
 3 <session-factory> 
 4   <property name="connection.provider">
 5 NHibernate.Connection.DriverConnectionProvider</property> 
 6   <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property> 
 7   <property name="connection.driver_class">
 8 NHibernate.Driver.SqlClientDriver</property> 
 9   <property name="connection.connection_string">Data Source=.;Initial Catalog=Company;Integrated Security=SSPI</property> 
10   <property name="show_sql">false</property> 
11 </session-factory> 
12 </hibernate-configuration>
View Code

 

 

6:現在是時候添加一些代碼來對數據庫映射模型進行CRUD操作NHibernate提供用於執行操作的各個類和接口其中一些是用於實現他們如下

ISession單線程,生命期較短的對象,代表應用程序和持久化層之間的一次對話。封裝了一個ADO.NET連接

ISessionFactory:它是Session的工廠,是ConnectionProvider的客戶。可以持有一個可選的(第二級)數據緩存,可以在進程級別或集群級別保存的可以在事物中重用的數據。。該方法的opensession()”提供了創建Session的功能每個數據庫要求一個會話工廠。執行是線程安全的,可以一直到應用程序的生存時間。

正如你可以看到下面的代碼,我們必須配置對象提供的配置文件的絕對路徑,也為其提供了目錄信息的所有映射文件將被保存(在opensession法)

iquery:這表示是NHibernate查詢一個對象。

 1 /// <summary> 
 2 /// class to perform the CRUD operations 
 3 /// </summary> 
 4 public class EmployeeInfoDAL 
 5 { 
 6 //Define the session factory, this is per database 
 7 ISessionFactory sessionFactory; 
 8 /// <summary> 
 9 /// Method to create session and manage entities 
10 /// </summary> 
11 /// <returns></returns> 
12 ISession OpenSession() 
13 { 
14   if (sessionFactory == null) 
15   { 
16    var cgf = new Configuration(); 
17    var data = cgf.Configure( 
18          HttpContext.Current.Server.MapPath( 
19             @"Models\NHibernate\Configuration\hibernate.cfg.xml")); 
20    cgf.AddDirectory(new System.IO.DirectoryInfo( 
21          HttpContext.Current.Server.MapPath(@"Models\NHibernate\Mappings"))); 
22    sessionFactory = data.BuildSessionFactory(); 
23   } 
24   return sessionFactory.OpenSession(); 
25 } 
26 public IList<EmployeeInfo> GetEmployees() 
27 { 
28   IList<EmployeeInfo> Employees; 
29   using (ISession session = OpenSession()) 
30   { 
31    //NHibernate query 
32    IQuery query = session.CreateQuery("from EmployeeInfo"); 
33    Employees = query.List<EmployeeInfo>(); 
34   } 
35   return Employees; 
36 } 
37 public EmployeeInfo GetEmployeeById(int Id) 
38 { 
39   EmployeeInfo Emp = new EmployeeInfo(); 
40   using (ISession session = OpenSession()) 
41   { 
42    Emp = session.Get<EmployeeInfo>(Id); 
43   } 
44   return Emp; 
45 } 
46 public int CreateEmployee(EmployeeInfo Emp) 
47 { 
48   int EmpNo = 0; 
49   using (ISession session = OpenSession()) 
50   { 
51    //Perform transaction 
52    using (ITransaction tran = session.BeginTransaction()) 
53    { 
54     session.Save(Emp); 
55     tran.Commit(); 
56    } 
57   } 
58   return EmpNo; 
59 }
60 public void UpdateEmployee(EmployeeInfo Emp) 
61 { 
62   using (ISession session = OpenSession()) 
63   { 
64    using (ITransaction tran = session.BeginTransaction()) 
65    { 
66     session.Update(Emp); 
67     tran.Commit(); 
68    } 
69   } 
70 }
71 public void DeleteEmployee(EmployeeInfo Emp) 
72 { 
73   using (ISession session = OpenSession()) 
74   { 
75    using (ITransaction tran = session.BeginTransaction()) 
76    { 
77     session.Delete(Emp); 
78     tran.Commit(); 
79    } 
80   } 
81 } 
82 } 
View Code

生成項目並確保它沒有錯誤。

 

7:添加新控制器,命名為“employeeinfocontroller”。添加下面的控制器類中的動作方法:

 1 using MVC4_Using_NHB.Models; 
 2 using System.Web.Mvc;
 3 namespace MVC4_Using_NHB.Controllers 
 4 { 
 5 public class EmployeeInfoController : Controller 
 6 { 
 7   EmployeeInfoDAL objDs; 
 8   public EmployeeInfoController() 
 9   { 
10    objDs = new EmployeeInfoDAL(); 
11   } 
12   // 
13   // GET: /EmployeeInfo/ 
14   public ActionResult Index() 
15   { 
16    var Employees = objDs.GetEmployees(); 
17    return View(Employees); 
18   } 
19 // 
20 // GET: /EmployeeInfo/Details/5
21 public ActionResult Details(int id) 
22 { 
23   return View(); 
24 } 
25 // 
26 // GET: /EmployeeInfo/Create 
27 public ActionResult Create() 
28 { 
29   var Emp = new EmployeeInfo(); 
30   return View(Emp); 
31 } 
32 // 
33 // POST: /EmployeeInfo/Create 
34 [HttpPost] 
35 public ActionResult Create(EmployeeInfo Emp) 
36 { 
37   try 
38   { 
39    objDs.CreateEmployee(Emp); 
40    return RedirectToAction("Index"); 
41   } 
42   catch 
43   { 
44    return View(); 
45   } 
46 } 
47 // 
48 // GET: /EmployeeInfo/Edit/5 
49 public ActionResult Edit(int id) 
50 { 
51   var Emp = objDs.GetEmployeeById(id); 
52   return View(Emp); 
53 } 
54 // 
55 // POST: /EmployeeInfo/Edit/5 
56 [HttpPost] 
57 public ActionResult Edit(int id, EmployeeInfo Emp) 
58 { 
59   try 
60   { 
61    objDs.UpdateEmployee(Emp); 
62    return RedirectToAction("Index"); 
63   } 
64   catch 
65   { 
66    return View(); 
67   } 
68 }
69 // 
70 // GET: /EmployeeInfo/Delete/5 
71 public ActionResult Delete(int id) 
72 { 
73   var Emp = objDs.GetEmployeeById(id); 
74   return View(Emp); 
75 } 
76 // 
77 // POST: /EmployeeInfo/Delete/5 
78 [HttpPost] 
79 public ActionResult Delete(int id,FormCollection collection) 
80 { 
81   try 
82   { 
83    var Emp = objDs.GetEmployeeById(id); 
84    objDs.DeleteEmployee(Emp);   
85    return RedirectToAction("Index"); 
86   } 
87   catch 
88   { 
89    return View(); 
90   } 
91 } 
92 } 
View Code

每個動作方法調用的employeeinfodal類定義的方法。現在只要為每個Action添加視圖方法,就可以運行連接到得到以下結果:

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM