参考:NHibernate中文帮助文档:.NET ORM框架全面指南-CSDN博客
NHibernate之旅系列文章导航 - 李永京 - 博客园
Your first NHibernate based application - NHibernate
创建Winform应用程序
创建Winform项目NHibernate,NuGet引入NHibernate包

创建数据库表
sql
USE MASTER
GO
IF EXISTS (SELECT TOP 1 1 FROM SYSDATABASES WHERE NAME='Demo')
DROP DATABASE Demo
GO
CREATE DATABASE Demo
GO
USE Demo
GO
IF EXISTS (SELECT TOP 1 1 FROM SYSOBJECTS WHERE NAME='TestTable')
DROP TABLE TestTable
GO
CREATE TABLE TestTable
(
Id NVARCHAR(50) PRIMARY KEY NOT NULL,
Contents NVARCHAR(100)
)
GO
创建实体类和xml文件

TestTable.cs
属性一定要加Virtual
cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NHibernateDemo.Entity
{
public class TestTable
{
public virtual string Id { get; set; }
public virtual string Contents { get; set; }
}
}
TestTable.hbm.xml
主键一定要用Id标签写,固定写法
XML
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="NHibernateDemo"
namespace="NHibernateDemo.Entity">
<class name="TestTable" table="TestTable">
<id name="Id" column="Id" type="String">
<generator class="native"/>
</id>
<property name="Contents" column="Contents" type="String"/>
</class>
</hibernate-mapping>

hibernate.cfg.xml
XML
<!-- 示例的hibernate.cfg.xml配置 -->
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<!-- 数据库连接设置 -->
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.Sql2008ClientDriver</property>
<property name="connection.connection_string">Server=.;Database=Demo;User Id=sa;Password=123;</property>
<!-- SQL方言 -->
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<!-- 映射文件的位置 -->
<mapping assembly="NHibernateDemo" resource="NHibernateDemo.Entity.TestTable.hbm.xml"/>
</session-factory>
</hibernate-configuration>

创建SessionFactory的类

cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
namespace NHibernateDemo
{
public class MySessionFactory
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
var configuration = new NHibernate.Cfg.Configuration();
_sessionFactory = configuration.Configure("hibernate.cfg.xml")
.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
查询

cs
private void BtnQuery_Click(object sender, EventArgs e)
{
using (var session = MySessionFactory.OpenSession())
{
var list = session.QueryOver<TestTable>().List().ToList();
}
}