Reputation: 1523
I'm struggling with a NHibernate mapping problem. I'm using Repository/UnitOfWork pattern, and I'm trying to cascade-persist my objects through update method. For an example: I can alter Foo, adding/updating/deleting Bar objects and it's all ok. But when I try to add Son and Daughter objects to "Bar", and update Foo (to persist Bar and its child objects), Son and Daughter objects are not persisted to DB, only Foo with all Bars (without Son/Daughter objects).
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" />
Where I'm doing it wrong? Thank you in advance!
Upvotes: 0
Views: 515
Reputation: 3810
Try the following test :
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;
Upvotes: 1