use NHibernate
go
CREATE TABLE users (
LogonID nvarchar(20) NOT NULL default '0',
Name nvarchar(40) default NULL,
Password nvarchar(20) default NULL,
EmailAddress nvarchar(40) default NULL,
PRIMARY KEY (LogonID)
)
go 数据表:users 二、总体介绍 项目名:WebNhibernate 界面:WebForm.aspx 具体表现文件:WebForm.aspx.cs 实体类文件:EntityClass.cs 映射文件:Userhbm.xml 配置文件:Web.config 三、创建Web界面
类型 | 对象名 | Text属性值 |
Label | Label1 | ID: |
Label | Label2 | 姓名: |
Label | Label3 | 密码: |
Label | Label4 | Email: |
Label | Labmessage | |
TextBox | TxtId | |
TextBox | TxtName | |
TextBox | TxtPassword | |
TextBox | TxtEmail | |
Button | ButSave | 添加 |
Button | ButDel | 删除 |
Button | ButUpdata | 修改 |
首先在文件头添加代码
using NHibernate;
using NHibernate.Cfg;
1.添加数据: 双击“添加“按钮 private void ButSave_Click(object sender, System.EventArgs e) { mCfg=new Configuration();//创建配置类 mCfg.AddXmlFile (System.Web.HttpContext.Current.Server.MapPath("Userhbm.xml"));//指明映射文件Userhbm.xml EntityClass vEntity=new EntityClass(); vEntity.Id=TxtId.Text; vEntity.UserName=TxtName.Text; vEntity.Password=TxtPassword.Text; vEntity.EmailAddress=TxtEmail.Text; ISession vSession= mCfg.BuildSessionFactory().OpenSession();//创建会话工厂, 一般来说应该使用一个单例对象来封装会话工厂. ITransaction vTransaction = vSession.BeginTransaction();//创建事物处理 try { vSession.Save(vEntity);//向数据库添加数据 vTransaction.Commit(); Labmessage.Text="OK"; } catch(Exception ex) { vTransaction.Rollback(); Labmessage.Text="Error"+ex.ToString(); } finally { vSession.Close(); } } 2.删除数据:
双击“删除“按钮
private void ButDel_Click(object sender, System.EventArgs e) { mCfg=new Configuration(); mCfg.AddXmlFile (System.Web.HttpContext.Current.Server.MapPath("Userhbm.xml")); ISession vSession= mCfg.BuildSessionFactory().OpenSession(); ITransaction vTransaction = vSession.BeginTransaction(); try { EntityClass vEntity=(EntityClass) vSession.Load(typeof(EntityClass),TxtId.Text);//查找数据表中所要记录 vSession.Delete(vEntity);//向数据库删除数据 vTransaction.Commit(); Labmessage.Text="OK"; } catch(Exception ex) { vTransaction.Rollback(); Labmessage.Text="Error"; } finally { vSession.Close(); } } 3.修改代码:
双击“修改“按钮
private void ButUpdata_Click(object sender, System.EventArgs e) { mCfg=new Configuration(); mCfg.AddXmlFile (System.Web.HttpContext.Current.Server.MapPath("Userhbm.xml")); ISession vSession= mCfg.BuildSessionFactory().OpenSession(); ITransaction vTransaction = vSession.BeginTransaction(); try { EntityClass vEntity=(EntityClass) vSession.Load(typeof(EntityClass),TxtId.Text); vEntity.UserName=TxtName.Text; vEntity.Password=TxtPassword.Text; vEntity.EmailAddress=TxtEmail.Text; vSession.Update(vEntity); //向数据库修改数据 vTransaction.Commit(); Labmessage.Text="OK"; } catch(Exception ex) { vTransaction.Rollback(); Labmessage.Text="Error"; } finally { vSession.Close(); } }