版本 nhibernate-nhibernate-core-3.3.0.CR1-14-ged0bffb
数据库 sqlite
总结几个简单步骤如下:
1.添加引用
将src\NHibernate\bin\Debug-2.0下的内容拷贝到待引用的应用根目录下,如debug
在项目中添加下面4个dll
Antlr3.Runtime.dll
Iesi.Collections.dll
NHibernate.dll
Remotion.Linq.dll
2设置session管理
----------------------------------------------------
/// <summary>
/// 获取会话
/// </summary>
/// <param name="strkey"></param>
/// <returns></returns>
public static ISession GetSession(string strkey)
{
if (!mdic_sessionFactory.ContainsKey(strkey))
{
lock (m_lockHelper)
{
if (!mdic_sessionFactory.ContainsKey(strkey))
{//加载配置
string path = Directory.GetCurrentDirectory() + "\\" + System.Configuration.ConfigurationSettings.AppSettings["hibernateconfig"];
//
Configuration m_configurationtmp = new Configuration();
XmlDocument xdoc = new XmlDocument();
xdoc.Load(path);
XmlNode xn =null ;
foreach (XmlNode xnsub in xdoc.DocumentElement.ChildNodes)
{
if (xnsub.Attributes["name"].Value == strkey)
{
xn = xnsub;
break;
}
}
XmlTextReader xtr = new XmlTextReader(new StringReader(xn.OuterXml));
m_configurationtmp.Configure(xtr);
mdic_sessionFactory[strkey] = m_configurationtmp.BuildSessionFactory();
}
}
}
return ((ISessionFactory)mdic_sessionFactory[strkey]).OpenSession();
}
}
------------------------------
hibernate.cfg.config
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="sqlite">
<property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
<property name="connection.connection_string">Data Source=D:\code\SummaryTool\CSPlugin\bin\Debug\test.db;Version=3;New=False;</property>
<property name="dialect">NHibernate.Dialect.SQLiteDialect</property>
<property name="query.substitutions">true=1;false=0</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.keywords">none</property>
<mapping assembly="ServiceCoreModel"/>
</session-factory>
</hibernate-configuration>
3.分页查询
/// <summary>
/// 分页查询
/// </summary>
/// <param name="querycondition">查询条件</param>
/// <param name="sortField">排序字段</param>
/// <param name="direction">升序or降序</param>
/// <param name="currentPageIndex">当前页码</param>
/// <param name="pageSize">页记录大小</param>
/// <param name="recordCount">总数</param>
/// <returns>查询结果集</returns>
public IList GetRecords(string querycondition, string sortField, bool direction, ref int currentPageIndex, int pageSize, ref int recordCount)
{
ISession _sessions = null;
ICriteria criteria = null;
ICriteria pageCrit = null;
try
{
_sessions = SessionManager.GetSession(ConnectStringKey);
criteria = _sessions.CreateCriteria(_queryobj);
QueryStringParse qp = new QueryStringParse();
//利用查询条件构造ICriteria
qp.SetICriteria(ref criteria, querycondition, _queryobj);
if (pageSize > 0)
{
//需要复制一份,一份查询总数,一份查询结果集,不能使用同一
//Criteria ,否则结果集没有列名信息
pageCrit = CriteriaTransformer.Clone(criteria );
recordCount = Convert.ToInt32(criteria.SetProjection(Projections.RowCount()).UniqueResult());
int totalpagenum = recordCount / pageSize + (recordCount % pageSize > 0 ? 1 : 0);
if (currentPageIndex == -1)
{
currentPageIndex = totalpagenum;
}
else
{
if (currentPageIndex > totalpagenum)
{
currentPageIndex = totalpagenum;
return (IList)null;
}
}
//设置排序
pageCrit.AddOrder(new Order(sortField, direction));
//设置分页
pageCrit.SetFirstResult((currentPageIndex - 1) * pageSize)//从第几条开始查找0表示第1条
.SetMaxResults(pageSize); //查找多少记录
}
//
return pageCrit.List();
}
catch
{
return (IList)null;
}
finally
{
}
}
4.查询结果转成表
private DataTable ORMObjectToTable(IList objl)
{
DataTable dt = null;
PropertyInfo[] piArr = null;
for (int i = 0; i < objl.Count; i++)
{
object obj = objl[i];
if (i == 0)
{
dt = new DataTable();
Type a = obj.GetType();
piArr = a.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (PropertyInfo pi in piArr)
{
dt.Columns.Add(pi.Name, pi.PropertyType);
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pi in piArr)
{
dr[pi.Name] = pi.GetValue(obj, null);
}
dt.Rows.Add(dr);
}
return dt;
}
5.表中行列重新组合
/// 转换表,将行组成列
/// </summary>
/// <param name="mea">一页数据及相关分页信息</param>
/// <returns></returns>Xml;
public MyEventArgs ReFormTable(MyEventArgs mea)
{
if (HTPageField.Count < 2)//指定要组合的值个数,如果小于2,不用拼凑行,否则需要将值对应行组合起来,如 1 a 0 ,1 b 0-> ? a b(转为标题)
//1 0 0,第1列可不显示
return mea;
MyJobItem mj = (MyJobItem)mea.MyArg;
DataTable dt = (DataTable)mj.Parametes["datatable"];
int imatch = 0;
if (dt != null)
{
imatch = dt.Rows.Count % HTPageField.Count;
}
else
{
return mea;
}
if (imatch != 0)
{
return mea;
}
DataTable tmpdt = new DataTable();
foreach (string strkey in HTPageField.Keys)
{
tmpdt.Columns.Add(strkey, typeof(string));
}
Hashtable htcmp = new Hashtable();
string strobjguid = string.Empty;
foreach (DataRow dr in dt.Rows)
{
strobjguid = dr["objguid"].ToString(); //每行的objguid不一样,根据objguid组装一行
if (!htcmp.ContainsKey(strobjguid))
{
DataRow newdr = tmpdt.NewRow();
htcmp[strobjguid] = "";
foreach (DataRow subdr in dt.Rows)
{
if (subdr["objguid"].ToString() == strobjguid)
{
newdr[subdr["objproperty"].ToString()] = subdr["objval"].ToString();
}
}
tmpdt.Rows.Add(newdr);
}
else
{
continue;
}
}
int itmp = 0;
//相关数量如总数、页数也要对应转换
mj.Parametes["datatable"] = tmpdt;
mj.Parametes["recordCount"] = (int)mj.Parametes["recordCount"] / HTPageField.Count;
itmp = (int)mj.Parametes["curPage"] / HTPageField.Count;
mj.Parametes["curPage"] = itmp > 0 ? itmp : 1;
itmp = (int)mj.Parametes["totalpagenum"] / HTPageField.Count;
mj.Parametes["totalpagenum"] = itmp > 0 ? itmp : 1;
return mea;
}