级联使用NHibernate更新一对多

时间:2013-05-15 14:44:30

标签: c# .net nhibernate orm nhibernate-mapping

我正在努力解决NHibernate映射问题。我正在使用Repository / UnitOfWork模式,我正在尝试通过update方法级联持久化我的对象。举个例子:我可以改变Foo,添加/更新/删除Bar对象,一切都好。但是当我尝试将Son和Daughter对象添加到“Bar”,并更新Foo(以持久化Bar及其子对象)时,Son和Daughter对象不会持久保存到DB,只有Foo与所有Bars(没有Son / Daughter对象)

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" />

我做错了什么?提前谢谢!

1 个答案:

答案 0 :(得分:1)

尝试以下测试:

    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;