NH一对一(唯一外键关联)
概述:
Nhibernate 表之间的几种关系不易把握,现根据个人学习,总结如下,共同学习.若有错误,请指出,不甚感谢!
NH一对一有三种设置方式,分别为:
单向主键关联映射
双向主键关联映射
唯一外键关联映射
本文以唯一外键关联映射作为学习.以Parent,Child为例.保存时先保存Parent,后保存Child(如果没有设置Cascade)
a.实体:
public class Parent
{
public Parent()
{
Child = new Child();
}
public virtual Guid Id
{
get;
set;
}
public virtual Child Child
{
get;
set;
}
}
public class Child
{
public Child()
{
}
public virtual Guid Id
{
get;
set;
}
public virtual Parent Parent
{
get;
set;
}
}
b.映射:
<class name="Parent">
<id name="Id">
<generator class="guid" />
</id>
//<one-to-one name=" Child " class=" Child " property-ref=" Parent "/>
<one-to-one name ="Child" class ="Child" cascade="all"></one-to-one>
</class>
<class name="Child">
<id name="Id">
<generator class="guid" />
</id>
<!--如果每一个子实例至多有一个父实例, 那么最自然的映射是一个one-to-many的关联关系.并且父亲是必须的,唯一-->
<many-to-one name="Parent" class="Parent" column="parent_id" unique="true"></many-to-one>
</class>
c.测试代码:
[Test]
public void CreateInitialDataOnetoOne()
{
using (ISession session = _sessionFactory.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
Parent p = new Parent();
Child c = new Child();
c.Parent = p;
p.Child = c;
session.Save(p);
transaction.Commit();
}
}
d.总结: