[NHibernate]基本配置與測試

目錄

寫在前面css

nhibernate文檔html

搭建項目web

映射文件sql

持久化類數據庫

輔助類緩存

數據庫設計與鏈接配置安全

測試session

總結多線程

寫在前面

一年前剛來這家公司,發現項目中使用的ORM是Nhibernate,這個以前確實沒接觸過,EF多少在項目中用過,想着既然都是ORM,應該語法上都差很少。當時也就是硬着頭皮上的,剛開始也只能經過模仿別人的代碼,再加上本身的理解,一些增刪改查的方法,確實也被本身給搞出來了,如今回頭想一想,在項目中,用到的那些方法基本上就一個樣,不多有變化。除非有些業務邏輯很是強的,本身搞不定,問一下同事,仍是能夠解決的。到如今使用Nhibernate也很長時間,中間多少也查過一些資料,從網上下的nhibernate文檔.docx,可是每次想去找的時候,總的在電腦上去找,比較麻煩,就乾脆記錄在博客中了,當時就是有哪些不明白的,能夠很方便的從裏面查,好比參數是什麼含義。也總結了一些,在使用過程遇到的問題。架構

如今項目告一段落,坐等爲客戶去部署了,也就有那麼點空閒時間,那就要系統的學習一下了。

發如今寫這篇文章的時候,說了本身的一些學習方式,發現越寫越多,就單獨成篇了,也就有了這篇文章——如何高效的利用博客園?

上篇文章,也算是nhibernate學習的開篇吧。

nhibernate文檔

[Nhibernate]體系結構

[NHibernate]ISessionFactory配置

[NHibernate]持久化類(Persistent Classes)

[NHibernate]O/R Mapping基礎

[NHibernate]集合類(Collections)映射 

[NHibernate]關聯映射

[NHibernate]Parent/Child

[NHibernate]緩存(NHibernate.Caches)

[NHibernate]NHibernate.Tool.hbm2net

[NHibernate]Nullables

[NHibernate]Nhibernate如何映射sqlserver中image字段

 

搭建項目

項目結構和映射文件

 

項目結構說明

採用傳統三層架構

Wolfy.Shop.Domain:數據實體和數據庫映射文件。也有人叫作領域層。

Wolfy.Shop.Data:數據層,存放數據庫的操做及Nhibernate輔助類。引用Iesi.Collections.dll,NHibernate.dll和類庫Wolfy.Shop.Domain

Wolfy.Shop.Business:業務邏輯類。引用類庫項目Wolfy.Shop.Domain,Wolfy.Shop.Data

Wolfy.Shop.WebSite:測試項目。需引用Iesi.Collections.dll,NHibernate.dll和類庫項目Wolfy.Shop.Domain,Wolfy.Shop.Business

Nhibernate最新版本爲4.0.1.GA,下載地址:http://nhforge.org/

解壓NHibernate-4.0.1.GA-bin.zip壓縮包,內容以下:

其中Confiuration_Templates文件夾內包括:

這些xml內爲數據庫鏈接配置文件模版,經過上圖也能夠發現nhibernate支持的數據庫種類仍是很全的。主流的數據庫已經都包括在內了。

那麼,我們打開MSSQL.cfg的文件看一下

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!-- 
 3 This template was written to work with NHibernate.Test.
 4 Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it 
 5 for your own use before compile tests in VisualStudio.
 6 -->
 7 <!-- This is the System.Data.dll provider for SQL Server -->
 8 <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
 9     <session-factory name="NHibernate.Test">
10         <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
11         <property name="connection.connection_string">
12             Server=(local);initial catalog=nhibernate;Integrated Security=SSPI
13         </property>
14         <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
15     </session-factory>
16 </hibernate-configuration>

經過上面的註釋部分我們能夠獲得一個信息,就是在項目中使用的話,須要將文件重命名爲hibernate.cfg.xml.

添加引用

一樣能夠經過Nuget進行添加,如圖:

持久化類

爲客戶實體建立持久化類

 1 namespace Wolfy.Shop.Domain.Entities
 2 {
 3     /// <summary>
 4     /// 描述:客戶實體,數據庫持久化類
 5     /// 建立人:wolfy
 6     /// 建立時間:2014-10-16
 7     /// </summary>
 8     public class Customer
 9     {
10         /// <summary>
11         /// 客戶id
12         /// </summary>
13         public virtual Guid CustomerID { get; set; }
14         /// <summary>
15         /// 客戶名字
16         /// </summary>
17         public virtual string CustomerName { get; set; }
18         /// <summary>
19         /// 客戶地址
20         /// </summary>
21         public virtual string CustomerAddress { get; set; }
22     }
23 }
注意NHibernate默認使用代理功能,要求持久化類不是sealed的,並且其公共方法、屬性和事件聲明爲virtual。在這裏,類中的字段要設置爲virtual,不然出現「

「NHibernate.InvalidProxyTypeException」類型的異常在 Wolfy.Shop.Data.dll 中發生,但未在用戶代碼中進行處理

其餘信息: The following types may not be used as proxies:

Wolfy.Shop.Domain.Entities.Customer: method get_CustomerID should be 'public/protected virtual' or 'protected internal virtual'

Wolfy.Shop.Domain.Entities.Customer: method set_CustomerID should be 'public/protected virtual' or 'protected internal virtual'

Wolfy.Shop.Domain.Entities.Customer: method get_CustomerName should be 'public/protected virtual' or 'protected internal virtual'

Wolfy.Shop.Domain.Entities.Customer: method set_CustomerName should be 'public/protected virtual' or 'protected internal virtual'

」異常。

 

編寫映射文件

編寫NHibernate配置文件智能提示的功能。只要在下載的NHibernate裏找到configuration.xsd和nhibernate-mapping.xsd兩個文件並複製到vs安裝目錄下,如C:\Program  Files\Microsoft Visual Studio 9.0\Xml\Schemas目錄便可。

此時,你在nhibernate的配置文件中就有智能提示功能了。

nhibernate如何知道持久化類和數據庫表的對應關係的呢?這就要經過映射文件來完成這個任務了,映射文件包含了對象/關係映射所需的元數據。元數據包含持久化類的聲明和屬性到數據庫的映射。映射文件告訴nhibernate它應該訪問數據庫裏面的哪一個表及使用表裏面的哪些字段。

那麼咱們編寫Customer持久化類的映射文件,注意映射文件以.hbm.xml結尾。如Customer.hbm.xml

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <!--assembly:程序集,namespace:命名空間-->
 3 <hibernate-mapping  xmlns="urn:nhibernate-mapping-2.2" assembly="Wolfy.Shop.Domain"  namespace="Wolfy.Shop.Domain.Entities">
 4   <class name="Wolfy.Shop.Domain.Entities.Customer,Wolfy.Shop.Domain" table="TB_Customer">
 5     <!--主鍵-->
 6     <id name="CustomerID" type="Guid" unsaved-value="null">
 7       <column name="CustomerID" sql-type="uniqueidentifier" not-null="true" unique="true"/>
 8       <generator class="assigned"></generator>
 9     </id>
10     <property name="CustomerName" type="String">
11       <column name="CustomerName" sql-type="nvarchar"  not-null="false"/>
12     </property>
13      <property name="CustomerAddress" type="String">
14       <column name="CustomerAddress" sql-type="nvarchar"  not-null="false"/>
15     </property>
16    
17   </class>
18 </hibernate-mapping>

這些東西該怎麼記?記住根節點hibernate,而且映射文件中要有主鍵id和property節點就能夠了,其餘的依賴vs的智能提示,就能夠了。
這裏須要養成一個習慣,就寫好映射文件,須要修改它的屬性

不然會出現,以下錯誤,而這個錯誤也是使用nhibernate最多見,因此養成一個好習慣,能提升你的開發效率:

輔助類

在使用以前,須要經過ISessionFactory得到ISession,ISessionFactory的詳細介紹能夠參考文檔[NHibernate]ISessionFactory配置 ,ISessionFactory是線程安全的,而ISession是非線程安全的。不少線程能夠同時訪問ISessionFactory,因此ISession要經過ISessionFactory打開,在全部的工做完成後,須要關閉。ISessionFactory一般是個線程安全的全局對象,只須要被實例化一次(可使用單例模式)。這裏編寫一個簡單的輔助類NHibernateHelper,用於建立ISessionFactory和配置ISessionFactory,並打開一個新的ISession的方法。代碼以下:

 1 using NHibernate;
 2 using NHibernate.Cfg;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace Wolfy.Shop.Data
10 {
11     /// <summary>
12     /// 描述:nhibernate輔助類
13     /// 建立人:wolfy
14     /// 建立時間:2014-10-16
15     /// </summary>
16     public class NHibernateHelper
17     {
18         private ISessionFactory _sessionFactory;
19         public NHibernateHelper()
20         {
21             //建立ISessionFactory
22             _sessionFactory = GetSessionFactory();
23         }
24         /// <summary>
25         /// 建立ISessionFactory
26         /// </summary>
27         /// <returns></returns>
28         public ISessionFactory GetSessionFactory()
29         {
30             //配置ISessionFactory
31             return (new Configuration()).Configure().BuildSessionFactory();
32         }
33         /// <summary>
34         /// 打開ISession
35         /// </summary>
36         /// <returns></returns>
37         public ISession GetSession()
38         {
39             return _sessionFactory.OpenSession();
40         }
41     }
42 
43 }
View Code

這裏需引入命名空間:NHibernate和NHibernate.Cfg。

數據庫設計與鏈接配置

數據表設計如圖所示:

建立數據表的sql

  1 USE [master]
  2 GO
  3 /****** Object:  Database [Shop]    Script Date: 2014/11/2 11:28:05 ******/
  4 CREATE DATABASE [Shop]
  5  CONTAINMENT = NONE
  6  ON  PRIMARY 
  7 ( NAME = N'Shop', FILENAME = N'F:\Database\Shop.mdf' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
  8  LOG ON 
  9 ( NAME = N'Shop_log', FILENAME = N'F:\Database\Shop_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
 10 GO
 11 ALTER DATABASE [Shop] SET COMPATIBILITY_LEVEL = 110
 12 GO
 13 IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
 14 begin
 15 EXEC [Shop].[dbo].[sp_fulltext_database] @action = 'enable'
 16 end
 17 GO
 18 ALTER DATABASE [Shop] SET ANSI_NULL_DEFAULT OFF 
 19 GO
 20 ALTER DATABASE [Shop] SET ANSI_NULLS OFF 
 21 GO
 22 ALTER DATABASE [Shop] SET ANSI_PADDING OFF 
 23 GO
 24 ALTER DATABASE [Shop] SET ANSI_WARNINGS OFF 
 25 GO
 26 ALTER DATABASE [Shop] SET ARITHABORT OFF 
 27 GO
 28 ALTER DATABASE [Shop] SET AUTO_CLOSE OFF 
 29 GO
 30 ALTER DATABASE [Shop] SET AUTO_CREATE_STATISTICS ON 
 31 GO
 32 ALTER DATABASE [Shop] SET AUTO_SHRINK OFF 
 33 GO
 34 ALTER DATABASE [Shop] SET AUTO_UPDATE_STATISTICS ON 
 35 GO
 36 ALTER DATABASE [Shop] SET CURSOR_CLOSE_ON_COMMIT OFF 
 37 GO
 38 ALTER DATABASE [Shop] SET CURSOR_DEFAULT  GLOBAL 
 39 GO
 40 ALTER DATABASE [Shop] SET CONCAT_NULL_YIELDS_NULL OFF 
 41 GO
 42 ALTER DATABASE [Shop] SET NUMERIC_ROUNDABORT OFF 
 43 GO
 44 ALTER DATABASE [Shop] SET QUOTED_IDENTIFIER OFF 
 45 GO
 46 ALTER DATABASE [Shop] SET RECURSIVE_TRIGGERS OFF 
 47 GO
 48 ALTER DATABASE [Shop] SET  DISABLE_BROKER 
 49 GO
 50 ALTER DATABASE [Shop] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
 51 GO
 52 ALTER DATABASE [Shop] SET DATE_CORRELATION_OPTIMIZATION OFF 
 53 GO
 54 ALTER DATABASE [Shop] SET TRUSTWORTHY OFF 
 55 GO
 56 ALTER DATABASE [Shop] SET ALLOW_SNAPSHOT_ISOLATION OFF 
 57 GO
 58 ALTER DATABASE [Shop] SET PARAMETERIZATION SIMPLE 
 59 GO
 60 ALTER DATABASE [Shop] SET READ_COMMITTED_SNAPSHOT OFF 
 61 GO
 62 ALTER DATABASE [Shop] SET HONOR_BROKER_PRIORITY OFF 
 63 GO
 64 ALTER DATABASE [Shop] SET RECOVERY FULL 
 65 GO
 66 ALTER DATABASE [Shop] SET  MULTI_USER 
 67 GO
 68 ALTER DATABASE [Shop] SET PAGE_VERIFY CHECKSUM  
 69 GO
 70 ALTER DATABASE [Shop] SET DB_CHAINING OFF 
 71 GO
 72 ALTER DATABASE [Shop] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF ) 
 73 GO
 74 ALTER DATABASE [Shop] SET TARGET_RECOVERY_TIME = 0 SECONDS 
 75 GO
 76 USE [Shop]
 77 GO
 78 /****** Object:  Table [dbo].[TB_Customer]    Script Date: 2014/11/2 11:28:05 ******/
 79 SET ANSI_NULLS ON
 80 GO
 81 SET QUOTED_IDENTIFIER ON
 82 GO
 83 CREATE TABLE [dbo].[TB_Customer](
 84     [CustomerID] [uniqueidentifier] NOT NULL,
 85     [CustomerName] [nvarchar](16) NULL,
 86     [CustomerAddress] [nvarchar](128) NULL,
 87     [Version] [int] NOT NULL,
 88  CONSTRAINT [pk_customerid] PRIMARY KEY CLUSTERED 
 89 (
 90     [CustomerID] ASC
 91 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
 92 ) ON [PRIMARY]
 93 
 94 GO
 95 /****** Object:  Table [dbo].[TB_Order]    Script Date: 2014/11/2 11:28:06 ******/
 96 SET ANSI_NULLS ON
 97 GO
 98 SET QUOTED_IDENTIFIER ON
 99 GO
100 CREATE TABLE [dbo].[TB_Order](
101     [OrderID] [uniqueidentifier] NOT NULL,
102     [CustomerID] [uniqueidentifier] NULL,
103     [OrderDate] [datetime] NULL,
104  CONSTRAINT [PK_TB_Order] PRIMARY KEY CLUSTERED 
105 (
106     [OrderID] ASC
107 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
108 ) ON [PRIMARY]
109 
110 GO
111 /****** Object:  Table [dbo].[TB_OrderProduct]    Script Date: 2014/11/2 11:28:06 ******/
112 SET ANSI_NULLS ON
113 GO
114 SET QUOTED_IDENTIFIER ON
115 GO
116 CREATE TABLE [dbo].[TB_OrderProduct](
117     [OrderID] [uniqueidentifier] NOT NULL,
118     [ProductID] [uniqueidentifier] NOT NULL
119 ) ON [PRIMARY]
120 
121 GO
122 /****** Object:  Table [dbo].[TB_Product]    Script Date: 2014/11/2 11:28:06 ******/
123 SET ANSI_NULLS ON
124 GO
125 SET QUOTED_IDENTIFIER ON
126 GO
127 CREATE TABLE [dbo].[TB_Product](
128     [ProductID] [uniqueidentifier] NOT NULL,
129     [Name] [nvarchar](128) NULL,
130     [Price] [decimal](18, 0) NULL,
131  CONSTRAINT [PK_TB_Product] PRIMARY KEY CLUSTERED 
132 (
133     [ProductID] ASC
134 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
135 ) ON [PRIMARY]
136 
137 GO
138 ALTER TABLE [dbo].[TB_Customer] ADD  DEFAULT ((1)) FOR [Version]
139 GO
140 ALTER TABLE [dbo].[TB_Order]  WITH CHECK ADD  CONSTRAINT [FK_TB_Order_TB_Customer] FOREIGN KEY([CustomerID])
141 REFERENCES [dbo].[TB_Customer] ([CustomerID])
142 GO
143 ALTER TABLE [dbo].[TB_Order] CHECK CONSTRAINT [FK_TB_Order_TB_Customer]
144 GO
145 ALTER TABLE [dbo].[TB_OrderProduct]  WITH CHECK ADD  CONSTRAINT [FK_TB_OrderProduct_TB_Order] FOREIGN KEY([OrderID])
146 REFERENCES [dbo].[TB_Order] ([OrderID])
147 GO
148 ALTER TABLE [dbo].[TB_OrderProduct] CHECK CONSTRAINT [FK_TB_OrderProduct_TB_Order]
149 GO
150 ALTER TABLE [dbo].[TB_OrderProduct]  WITH CHECK ADD  CONSTRAINT [FK_TB_OrderProduct_TB_Product] FOREIGN KEY([ProductID])
151 REFERENCES [dbo].[TB_Product] ([ProductID])
152 GO
153 ALTER TABLE [dbo].[TB_OrderProduct] CHECK CONSTRAINT [FK_TB_OrderProduct_TB_Product]
154 GO
155 USE [master]
156 GO
157 ALTER DATABASE [Shop] SET  READ_WRITE 
158 GO
View Code

nhibernate配置,也就是數據庫配置:

這裏使用的是SQL Server2012,因此咱們使用MSSQL.cfg.xml文件,重命名爲hibernate.cfg.xml.

注意需根據本身數據庫的實例名修改,並添加mapping節點,其餘的設置,可根據須要進行添加。這裏採用最簡單的一種方式,關於nhibernate的配置參數,可參考文檔中的說明。

 1  1 <?xml version="1.0" encoding="utf-8" ?>
 2  2 <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
 3  3   <session-factory>
 4  4     <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
 5  5     <property name="connection.connection_string">
 6  6       server=.;database=shop;uid=sa;pwd=sa
 7  7     </property>
 8  8     <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
 9  9     <mapping  assembly="Wolfy.Shop.Domain"/>
10 10   </session-factory>
11 11 </hibernate-configuration>

修改後,將hibernate.cfg.xml拷入Wolfy.Shop.WebSite項目,並修改其屬性:

不然會出現以下異常:

數據層和業務邏輯層代碼

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Wolfy.Shop.Domain.Entities;
 7 using NHibernate;
 8 using NHibernate.Linq;
 9 using NHibernate.Cfg;
10 using System.Linq.Expressions;
11 namespace Wolfy.Shop.Data
12 {
13     /// <summary>
14     /// 描述:客戶數據層類,操做數據庫
15     /// 建立人:wolfy
16     /// 建立時間:2014-10-16
17     /// </summary>
18     public class CustomerData
19     {
20         /// <summary>
21         /// 添加客戶
22         /// </summary>
23         /// <param name="customer">客戶實體</param>
24         /// <returns>是否添加成功 </returns>
25         public bool AddCustomer(Customer customer)
26         {
27 
28             try
29             {
30                 NHibernateHelper nhibernateHelper = new NHibernateHelper();
31                 var session = nhibernateHelper.GetSession();
32                 session.SaveOrUpdate(customer);
33                 session.Flush();
34                 return true;
35             }
36             catch (Exception ex)
37             {
38                 throw ex;
39             }
40         }
41         /// <summary>
42         /// 根據條件獲得客戶信息集合
43         /// </summary>
44         /// <param name="where">條件</param>
45         /// <returns>客戶信息集合</returns>
46         public IList<Customer> GetCustomerList(Expression<Func<Customer, bool>> where)
47         {
48             try
49             {
50                 NHibernateHelper nhibernateHelper = new NHibernateHelper();
51                 ISession session = nhibernateHelper.GetSession();
52                 return session.Query<Customer>().Where(where).ToList();
53             }
54             catch (Exception ex)
55             {
56                 throw ex;
57             }
58         }
59     }
60 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Linq.Expressions;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 using Wolfy.Shop.Data;
 8 using Wolfy.Shop.Domain.Entities;
 9 
10 namespace Wolfy.Shop.Business
11 {
12 
13     /// <summary>
14     /// 描述:客戶信息業務邏輯層
15     /// 建立人:wolfy
16     /// 建立時間:2014-10-17
17     /// </summary>
18     public class CustomerBusiness
19     {
20         private CustomerData _customerData;
21         public CustomerBusiness()
22         {
23             _customerData = new CustomerData();
24         }
25         /// <summary>
26         /// 添加客戶
27         /// </summary>
28         /// <param name="customer">客戶實體</param>
29         /// <returns>是否添加成功 </returns>
30         public bool AddCustomer(Customer customer)
31         {
32             return _customerData.AddCustomer(customer);
33         }
34         /// <summary>
35         /// 根據條件獲得客戶信息集合
36         /// </summary>
37         /// <param name="where">條件</param>
38         /// <returns>客戶信息集合</returns>
39         public IList<Customer> GetCustomerList(Expression<Func<Customer, bool>> where)
40         {
41             return _customerData.GetCustomerList(where);
42         }
43     }
44 }
View Code

 測試

爲了之後使用方便,在這裏使用webform項目做爲測試,經過單擊「添加」按鈕,向數據庫中插入記錄,

頁面

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomerManager.aspx.cs" Inherits="Wolfy.Shop.WebSite.CustomerManager" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 8     <title></title>
 9     <style type="text/css">
10         .main {
11             border: 1px solid #0094ff;
12             margin: 50px auto;
13             width: 600px;
14         }
15 
16         .table {
17             border: 1px solid #0094ff;
18             border-collapse: collapse;
19             width: 98%;
20             text-align: center;
21             margin:5px auto;
22         }
23 
24             .table th {
25                 background-color: lightgray;
26             }
27             .table tr td {
28                  border: 1px solid #0094ff;
29             }
30     </style>
31 </head>
32 <body>
33     <form id="form1" runat="server">
34         <div class="main">
35             <asp:Button runat="server" ID="btnAdd" Text="添加" OnClick="btnAdd_Click" />
36             <div>
37                 <asp:Repeater runat="server" ID="rptCustomerList">
38                     <HeaderTemplate>
39                         <table class="table">
40                             <tr>
41                                 <th>姓名</th>
42                                 <th>姓名</th>
43                                 <th>地址</th>
44                             </tr>
45                     </HeaderTemplate>
46                     <ItemTemplate>
47                         <tr>
48                             <td><%#Container.ItemIndex+1 %></td>
49                             <td><%#Eval("CustomerName") %></td>
50                             <td><%#Eval("CustomerAddress") %></td>
51                         </tr>
52                     </ItemTemplate>
53                     <FooterTemplate>
54                         </table>
55                     </FooterTemplate>
56                 </asp:Repeater>
57             </div>
58         </div>
59     </form>
60 </body>
61 </html>
CustomerManager。aspx
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using Wolfy.Shop.Domain.Entities;
 8 
 9 namespace Wolfy.Shop.WebSite
10 {
11     public partial class CustomerManager : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15             if (!IsPostBack)
16             {
17                 RepeaterDataBind();
18             }
19         }
20         private void RepeaterDataBind()
21         {
22             Business.CustomerBusiness customerBusiness = new Business.CustomerBusiness();
23             this.rptCustomerList.DataSource = customerBusiness.GetCustomerList(c => 1 == 1);
24             this.rptCustomerList.DataBind();
25         }
26         /// <summary>
27         /// 添加客戶信息
28         /// </summary>
29         /// <param name="sender"></param>
30         /// <param name="e"></param>
31         protected void btnAdd_Click(object sender, EventArgs e)
32         {
33             var customer = new Customer() { CustomerName = "wolfy", CustomerAddress = "北京 海淀", CustomerID = Guid.NewGuid() };
34             Business.CustomerBusiness customerBusiness = new Business.CustomerBusiness();
35             if (customerBusiness.AddCustomer(customer))
36             {
37                 this.RepeaterDataBind();
38             }
39         }
40     }
41 }
CustomerManager.aspx.cs

界面

經過SQL Server Profiler查看生成的sql語句

經過監控到的sql語句,也能夠看到使用nhibernate插入數據時,數據庫中是經過存儲過程進行插入數據的。

總結

本文簡單介紹了使用nhibernate的一些配置,給個人感受是,在使用時只要配置正確,其餘的增刪改查什麼的也就沒什麼難的了。在配置nhibernate的時候,有些細節須要注意。好比映射文件和nhibernate的配置文件的屬性須要進行修改。

參考文章

http://www.cnblogs.com/lyj/archive/2008/10/14/1310913.html#comment_tip

相關文章
相關標籤/搜索