使用NHibernate进行一对多更新
本文关键字:一对多 更新 NHibernate 使用 | 更新日期: 2023-09-27 18:13:37
我正在努力解决一个NHibernate映射问题。我正在使用Repository/UnitOfWork模式,并且我正在尝试通过更新方法级联持久化我的对象。例如:我可以修改Foo,添加/更新/删除Bar对象,这一切都没问题。但是当我尝试添加儿子和女儿对象到"酒吧",并更新Foo(持久化酒吧及其子对象),儿子和女儿对象不持久化到DB,只有Foo与所有酒吧(没有儿子/女儿对象)。
public class Foo
{
public int FooID {get; set;}
public string Name {get; set;}
public virtual IList<Bar> Bars {get; set;}
public Foo(){}
}
public class Bar
{
public int BarID {get; set;}
public string Name {get; set;}
public Foo Foo {get; set;}
public virtual IList<Son> Sons {get; set;}
public virtual IList<Daughter> Daughters {get; set;}
public Bar(){}
}
public class Son
{
public int SonID {get; set;}
public string Name {get; set;}
public virtual Bar Bar {get; set;}
public Son(){}
}
public class Daughter
{
public int DaughterID {get; set;}
public string Name {get; set;}
public virtual Bar Bar {get; set;}
public Daughter(){}
}
//on Foo.hbm.xml I have:
...
<bag name="Bar" table="Bar" inverse="true" cascade="all-delete-orphan" lazy="false">
<key column="FooID" />
<one-to-many class="Bar" />
</bag>
//on Bar.hbm.xml I have
...
<many-to-one name="Foo" column="FooID" class="Foo" lazy="false" />
<bag name="Son" table="Son" inverse="true" cascade="all-delete-orphan" lazy="false">
<key column="SonID" />
<one-to-many class="Son" />
</bag>
<bag name="Daughter" table="Daughter" inverse="true" cascade="all-delete-orphan" lazy="false">
<key column="DaughterID" />
<one-to-many class="Daughter" />
</bag>
//on Son/Daughter.hbm.xmlI have
...
<many-to-one name="Bar" column="BarID" class="Bar" lazy="false" />
我哪里做错了?提前感谢!
尝试以下测试:
var newFoo = new Foo();
var newBar = new Bar();
var newSon = new Son();
_session.Save(newBar);
newSon.Bar = newBar;
newBar.Sons.Add(newSon);
Foo.Bar = newBar;