NHibernate has become the. NET mainstream ORM framework, and of course, if you need to use nhibernate in development, we will typically encapsulate it once to make it easier to use in the project and to have a global control over the NHibernate. And the package of nhibernate is not so simple, for example, NHibernate can not do the encapsulation of the layer, meaning that in other layers using the encapsulated code, but also need to refer to nhibernate, such as the general IQuery condition query, If you need to sort or dynamic conditions, you need to pass icriterion to the call layer to set up, of course, if it is hql can use stitching method, but do not recommend this method of splicing in the UI layer, so there is no difference between SQL.
The following code is a bit of encapsulation that I used in the project I was studying, and of course not rigorously tested, if there is a bug please let me know.
The first is the encapsulation of NHibernate's sessionfactory, which is very similar.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Web;
6 using NHibernate;
7 using Nhibernate.cfg;
8 using System.Collections;
9
Ten namespace LBC. Permission.dal
11 {
12
public class Nhsessionfactory
14 {
The private static readonly object lockobj = new Object ();
private static Nhsessionfactory instance = NULL;
-Private static Isessionfactory factory;
18
Private Nhsessionfactory () {}
20
-public static Nhsessionfactory Instance
22 {
Get
24 {
if (instance = = null)
26 {
Lock (Lockobj)
28 {
if (instance = = null)
30 {
Instance = new Nhsessionfactory ();
Configuration cfg = new configuration ();
Factory = cfg. Configure (). Buildsessionfactory ();
34}
35}
36}
Panax Notoginseng return instance;
38}
39}
40
ISession Public getcurrentsession ()
42 {
Factory return. Getcurrentsession ();
44}
45
ISession opensession ()
47 {
Factory return. Opensession ();
49}
50
Wuyi Public Isessionfactory Sessionfactory
52 {
A Get
54 {
return factory;
56}
57}
58
59}
60}
Then the encapsulation of common methods
1 public partial class DataAccess
2 {
3 Private ISession session;
4
5 Public DataAccess ()
6 {
7 session = NHSessionFactory.Instance.GetCurrentSession ();
8}
9
Ten #region Transaction
11
public void Transaction (action action)
13 {
ITransaction transaction = session. BeginTransaction ();
Try
16 {
+ action ();
Transaction.commit ();
19}
Catch
21 {
Transaction. Rollback ();
At a throw;
24}
25}
26
public void Transaction (Action action, System.Data.IsolationLevel IsolationLevel)
28 {
ITransaction transaction = session. BeginTransaction (IsolationLevel);
Try
31 {
Action ();
Transaction.commit ();
34}
Catch
36 {
Panax Notoginseng transaction. Rollback ();
(a) throw;
39}
40}
41
#endregion
43}
Transferred from: http://www.cnblogs.com/liubiaocai/archive/2011/09/17/2179350.html
NHibernate Uniform class Encapsulation code