今天进一步学习了NHibernate,研究了如何添加及查找有外键关系的表。
public class DeptInfo
{
public virtual string DeptId { get; set; }
public virtual string DeptName { get; set; }
}
其对应的配置
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Test.Model.DeptInfo, Test.Model" table="DeptInfo">
<id name="DeptId" type="String" unsaved-value="null">
<column name="DeptId" length="50" sql-type="String" not-null="true" unique="true" index="PK_DeptInfo"/>
<generator class="assigned" />
</id>
<property name="DeptName" type="String">
<column name="DeptName" length="50" sql-type="varchar" not-null="true"/>
</property>
</class>
</hibernate-mapping>
public class UserInfo
{
public virtual string UserID { get; set; }
public virtual string UserName { get; set; }
public virtual string Email { get; set; }
public virtual DeptInfo DeptInfo { get; set; }
}
其对应的配置
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Test.Model.UserInfo, Test.Model" table="UserInfo">
<id name="UserID" type="string" unsaved-value="null">
<column name="UserID" length="50" sql-type="String" not-null="true" unique="true" index="PK_UserInfo"/>
<generator class="assigned" />
</id>
<property name="UserName" type="String">
<column name="UserName" length="50" sql-type="varchar" not-null="true"/>
</property>
<property name="Email" type="String">
<column name="Email" length="50" sql-type="String" not-null="true"/>
</property>
<many-to-one name="DeptInfo" class= "Test.Model.DeptInfo,Test.Model" column="DeptId"/>
</class>
</hibernate-mapping>
部分代码如下(上篇我对NHibernate的理解里已经讲述了,这里就不再重复了):
添加用户代码:
DeptInfo deptInfo = new DeptInfo();
deptInfo.DeptId = ddlDept.SelectedValue;
UserInfo userInfo = new UserInfo();
userInfo.DeptInfo = deptInfo;
userInfo.UserID = txtUserID.Text;
userInfo.UserName = txtUserName.Text;
userInfo.Email = txtEmail.Text;
session.Save(u);
查找用户代码:
UserInfo userInfo = (UserInfo)session.Get(typeof(UserInfo), "1");//查找唯一一条记录,其中1为主键的值UserId
IList<UserInfo> lstUserInfo = session.CreateQuery("from UserInfo").List<UserInfo>();//查找所有记录
然后想将DeptName显示在界面上,只能如下:
DataTable dt = new DataTable();
dt.Columns.Add("UserName");
dt.Columns.Add("DeptName");
foreach (UserInfo userInfo in u)
{
DataRow dr = dt.NewRow();
dr["UserName"] = userInfo.UserName;
dr["DeptName"] = userInfo.DeptInfo.DeptName;
dt.Rows.Add(dr);
}
2012.2.16于上海 章松山