本例子为在c#中使用Nhibernate对数据库进行操作,数据库为sqlserver2008,开发环境为VS2013。整个程序为示例程序,希望能为大家提供帮助。
首先建立数据库文件:
CREATE TABLE [dbo].[customer](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] varchar NULL,
[age] [int] NULL,
CONSTRAINT [PK_customer] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
这边截取数据库的建立代码,也可以通过可视化界面建立。
建立工程,名为Nhibnet_test,引入,Iesi.Collections.dll、NHibernate.dll。工程中建立cfg文件夹,Dao文件夹,Mappings文件夹。
cfg文件夹中建立hibernate.cfg.xml文件。
代码如下:
NHibernate.Driver.SqlClientDriver
Data Source=.;Initial Catalog=nihibnet_test;Integrated Security=True;
10
NHibernate.Dialect.MsSql2008Dialect
60
update
true 1, false 0, yes ‘Y’, no ‘N’
Dao文件中建立文件customer.cs,功能为增、删、改、查代码如下:
namespace Nhibnet_test.Dao
{
class customer
{
private ISession session;
public customer(ISession session)
{
this.session = session;
}
public void Insertcsutomer(SysBase.Entities.customer cs)
{
ITransaction transaction = this.session.BeginTransaction();
//Console.WriteLine(tcalculationX.Name);
this.session.Save(cs);
transaction.Commit();
}
public void Deletecsutomer(SysBase.Entities.customer cs)
{
ITransaction transaction = this.session.BeginTransaction();
this.session.Delete(cs);
transaction.Commit();
}
public void Updatecsutomer(SysBase.Entities.customer cs)
{
ITransaction transaction = this.session.BeginTransaction();
this.session.Update(cs);
transaction.Commit();
}
public IList<SysBase.Entities.customer> GetAllcustomer(bool evict)
{
IList<SysBase.Entities.customer> list = this.session.CreateQuery("from customer").List<SysBase.Entities.customer>();
if (evict)
{
foreach (SysBase.Entities.customer tcalculation in list)
{
this.session.Evict(tcalculation);
}
}
return list;
}
public SysBase.Entities.customer GetAllcustomerByID(string id, bool evict)
{
IQuery query = this.session.CreateQuery("select c from customer as c where c.Id= :x");
SysBase.Entities.customer cs = (SysBase.Entities.customer)query.UniqueResult();
if (evict)
{
this.session.Evict(cs);
}
return cs;
}
public IList<SysBase.Entities.customer> GetTcustomerByselfdefin(IQuery query, bool evict)
{
IList<SysBase.Entities.customer> list = query.List<SysBase.Entities.customer>();
if (evict)
{
foreach (SysBase.Entities.customer cs in list)
{
this.session.Evict(cs);
}
}
return list;
}
}
}