NHibernate不坚持儿童对象
问题描述:
我有两个对象,父母和孩子。我坚持对象父parent1。我想创建一个新的Child对象,将其Parent属性设置为“parent1”并将其添加到parent1上的Childs集合。NHibernate不坚持儿童对象
家长
public class Parent: IEquatable<Parent>
{
public virtual IList<Child> Childs{ get; set; }
...
}
儿童
public class Child: IEquatable<Child>
{
public virtual Parent Parent { get; set; }
...
}
Parent.hbm.xml
<bag name="Childs" lazy="false" inverse="true" cascade="all">
<key column="Id" />
<one-to-many class="Child" />
</bag>
Child.hbm.xml
<many-to-one name="Parent">
<column name="Parent" sql-type="int" not-null="true" />
</many-to-one>
运行此代码
var child = new Child();
child.Condition = value;
Parent parent= m_parentmanager.Get(2); // "parent1"
parent.Childs.Add(child);
child.Parent = parent;
m_childsmanager.Save(child);
当我再次拨打 “父父= m_parentmanager.Get(2)” 下面几行,我可以在调试模式下看到该集合Childs是空的。我有一个按钮来添加孩子到家长(收集孩子)在我的视图。当我第一次按下按钮时,此代码会运行,但Childs集合是空的。当我第二次按下按钮时,Child实体被添加到Childs集合中。所有其他按钮点击也不会将任何新的Child实体添加到集合中。
有人可以告诉我我做错了什么吗?
答
在DB中,父项与子项和子项对父项的关系 - 由一个(相同)列定义。它是子表中的外键。并且必须在映射中使用双方
// column must be the one, which is used for many-to-one
<bag name="Childs" lazy="false" inverse="true" cascade="all">
<!--<key column="Id" />-->
<key column="Parent" />
<one-to-many class="Child" />
</bag>
// column Parent represents the relation, it must be used for Childs coll as well
<many-to-one name="Parent">
<column name="Parent" sql-type="int" not-null="true" />
</many-to-one>
另外,集合应该加载懒惰。将它们映射为渴望是没有好处的。而是在查询中加载它,而不是强制映射。
映射的其余部分似乎没问题 - 反转,并且双方都分配在C#中...它应该工作
它的工作原理!非常感谢你 !!! :) –
你能否帮助我与映射的其他问题?你看起来像你知道你在做什么... [链接](http://*.com/questions/40708309/nhibernate-mapping-class-with-attribute-of-same-type) –