I have a Parent class with two lists of Child classes
public class Parent
{
...
public virtual ICollection<Foo> Foo{ get; set; }
public virtual ICollection<Bae> Bar{ get; set; }
}
public class Foo
{
...
public virtual Parent Parent{ get; set; }
}
public class Bar
{
...
public virtual Parent Parent{ get; set; }
}
The mappings are
public ParentMap()
{
...
HasMany(m => m.Foo).AsSet().Cascade.All();
HasMany(m => m.Bar).AsSet().Cascade.All();
}
public FooMap()
{
...
References(m => m.Parent);
}
public BarMap()
{
...
References(m => m.Parent);
}
Whenever I save the parent object I get
INSERT Parent ...
INSERT Foo with Parent_id set to NULL
INSERT Bar with Parent_id set to NULL
UPDATE Foo set Parent_id to Parent id
UPDATE Bar set Parent_id to Parent id
Is there a way apart from setting the relationship to Inverse to avoid the extra update?
If you have a bidirectional assiciation you should set the HasMany side to inverse, this is the most common way.
Another possibility is setting the parent reference to
Not.Insert().Not.Update(), then the parent property will be completely ignored for insert/updates.If you don’t need the reference from child to parent just remove it from the class and mapping so you only have the collection.
For the second and third way you can additionally set
Not.KeyNullable()on the HasMany, this makes sure that NHibernate inserts the new row with the parent ID already set and avoids the additional update statement (this feature requires NHibernate 3.2.0).