上一个例子是一个简单表的插入数据。
在实际中很多表都是使用Id int来做自增量来实现的。
Users结构是
GO
/****** 对象: Table [dbo].[Users] 脚本日期: 09/17/2008 21:51:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[Name] [nvarchar](40) COLLATE Chinese_PRC_CI_AS NULL,
[Password] [nvarchar](20) COLLATE Chinese_PRC_CI_AS NULL,
[EmailAddress] [nvarchar](40) COLLATE Chinese_PRC_CI_AS NULL,
[LastLogon] [datetime] NULL,
[Id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
User.cs
{
private string userName;
private string password;
private string emailAddress;
private DateTime lastLogon;
private System.Int32 id;
public User()
{
}
public System.Int32 Id
{
get { return id; }
set { id = value; }
}
public string UserName
{
get { return userName; }
set { userName = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public string EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
public DateTime LastLogon
{
get { return lastLogon; }
set { lastLogon = value; }
}
}
User.hbm.xml
用的是自动编号,所以,要将 <generator class="assigned" />改为 <generator class="identity"" />
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Nhibernate1.User, Nhibernate1" table="users" lazy="false">
<id name="Id" column="Id" type="Int32">
<generator class="identity" />
</id>
<property name="UserName" column="Name" type="String" length="40"/>
<property name="Password" type="String" length="20"/>
<property name="EmailAddress" type="String" length="40"/>
<property name="LastLogon" type="DateTime"/>
</class>
</hibernate-mapping>
cs
添加时候不写入id的属性,因为数据库已经自动增加。
删除代码如下
private void del_Click(object sender, EventArgs e)
{
Configuration cfg = new Configuration();
cfg.AddAssembly("ClassLibrary");
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
User newUser = (User)session.Load(typeof(User), 2);
// Tell NHibernate that this object should be saved
session.Delete(newUser);
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
MessageBox.Show("OK!");
}
选择数据并绑定DataGridView
Configuration cfg = new Configuration();
cfg.AddAssembly("Nhibernate1");
ISessionFactory factory = cfg.BuildSessionFactory();
ISession session = factory.OpenSession();
ITransaction transaction = session.BeginTransaction();
myds=new DataSet();
System.Collections.IList list = session.CreateQuery("select u from User as u").List();
this.dataGridView1.DataSource = list;
session.Close();
MessageBox.Show("OK!");