I’ve got an Order class that contains OrderItems. When I save the Order class, the database is populated with the Order information, but none of the child OrderItems are saved to their respective tables. Here’s what the Order mapping looks like:
<class name="Order" table="Orders">
<id name="OrderID" column="OrderID" type="Int64" unsaved-value="0">
<generator class="identity"/>
</id>
<list name="OrderItems" table="OrderItems" inverse="true" >
<key column="OrderID"/>
<index column="OrderItemID" />
<one-to-many class="OrderItem" />
</list>
Here’s what the OrderItem mapping looks like:
<class name="OrderItem" table="OrderItems">
<id name="OrderItemID" column="OrderItemID" type="Int64" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="OrderID" />
<many-to-one name="Order" class="Order" column="OrderID" not-null="true" />
</class>
Here’s what the code to save the Order looks like:
if (o.CreatedBy == null || o.CreatedBy == string.Empty) {
o.CreatedBy = userID.ToString();
foreach (OrderItem oi in obj.OrderItems) {
oi.CreatedBy = userID.ToString();
oi.ModifiedBy = userID.ToString();
oi.ModifiedOn = DateTime.Now;
}
}
o.ModifiedBy = userID.ToString();
o.ModifiedOn = DateTime.Now;
ISession session = NHibernateHelper.GetCurrentSession();
ITransaction tx = session.BeginTransaction();
session.Save(o);
tx.Commit();
NHibernateHelper.CloseSession();
Any idea why the child OrderItems aren’t being saved?
To make the update command propagate on all children of an Order, you need to enable cascading updates on your collection mapping:
Additionally, since the collection is marked as “inverse” and – in the example above – you’re trying to save a new Order, you’ll need to individually update the OrderItem.Order property and issue an Update() call on the item: