NHibernate不保存对象的项集合

时间:2009-04-17 14:27:41

标签: nhibernate collections

我有一个包含OrderItems的Order类。保存Order类时,数据库将填充Order信息,但没有子OrderItems保存到各自的表中。以下是Order映射的样子:

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

这是OrderItem映射的样子:

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

以下是保存订单的代码:

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();

知道为什么没有保存子OrderItems?

2 个答案:

答案 0 :(得分:7)

要使更新命令在订单的所有子项上传播,您需要在集合映射上启用级联更新:

<list name="OrderItems" table="OrderItems" inverse="true" cascade="all">
  <key column="OrderID"/>
  <index column="OrderItemID" />
  <one-to-many class="OrderItem" />
</list>

此外,由于集合标记为“反向”,并且 - 在上面的示例中 - 您尝试保存新订单,您需要单独更新OrderItem.Order属性并对项目发出Update()调用:

using(ITransaction tx = session.BeginTransaction()){
    session.Save(o);
    foreach(var item in o.OrderItems){
        item.Order = o;
        session.SaveOrUpdate(item);
    }
    tx.Commit();
}

答案 1 :(得分:5)

cascade="all"添加到您的收藏集映射。