是否可以使用nhibernate引用子对象中的父对象?到目前为止我一直在做的是将父Id放在子类中,允许我确定任何子节点的父节点在运行时。
有人告诉我,我可以改为引用我孩子的整个父对象,而不仅仅是父ID,而不会遇到递归问题。
我目前所做的是:
Child child = (Child)session.Get(typeof(Child), childId);
然后我可以这样抓住我的parentId:
int parentId = child.ParentId;
我想做的是:
Child child = (Child)session.Get(typeof(Child), childId);
int parentId = child.**Parent**.Id;
string parentName = child.**Parent**.Name
以下是我如何定义课程的示例
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
// A list of child objects
public IList<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; } // this is what I use now
// public Parent MyParent { get; set; } // this is what I want to use
}
我的nHibernate映射文件:
<class name="Parent" table="parents" lazy="false">
<id name="Id">
<generator class="identity" />
</id>
<property name="Name" />
<bag name="Children" cascade="all" lazy="false" >
<key column="ParentId" />
<one-to-many class="Child"/>
</bag>
<!-- Do I put anything in here to refer to my parent object in my child object?-->
</class>
<class name="Child" table="Children" lazy="false">
<id name="Id">
<generator class="identity" />
</id>
<property name="ParentId" />
<property name="Name" />
<!-- Do I put anything in here to refer to my parent object in my child object?-->
</class>
感谢任何帮助!
答案 0 :(得分:2)
<!-- Set inverse to true on the one-to-many to tell
NHibernate this relation is mapped from both sides -->
<bag name="Children" cascade="all" lazy="false" inverse="true">
<key column="ParentId" />
<one-to-many class="Child"/>
</bag>
<class name="Child" table="Children" lazy="false">
<id name="Id">
<generator class="identity" />
</id>
<property name="ParentId" />
<!-- Use this to map the Parent object -->
<many-to-one name="MyParent" class="Parent" column="ParentId"/>
<property name="Name" />
</class>