NHibernate的。不能将两个孩子添加到父母

时间:2011-03-23 15:04:37

标签: c# .net nhibernate orm

我有共同的父\子场景:

public class Order : AdvancedBaseOrder
{

    ICollection<ProducerRelation> producers = new List<ProducerRelation>();
    public virtual ICollection<ProducerRelation> Producers
    {
        get { return producers; }
        set { producers = value; }
    }
}

public class ProducerRelation : BaseProducerRelation
{
    public virtual Order Order { get; set; }
    public virtual int Number { get; set; }
}

映射:

Order.hbm.xml
....
<set name="Producers" cascade="all-delete-orphan" inverse="true">
  <key column="order_id"/>
  <one-to-many class="ProducerRelation,Avtobus66.Core"/>
</set>
....


ProducerRelation.hbm.xml
....
 <many-to-one name="Order" class="Order, Avtobus66.Core" column="order_id" cascade="none"/>
<property name="Number" >
  <column name="number"/>
</property>
....

当我运行此代码时:

            Order order = (Order)session.Get(typeof(Order), 23);
            var a = new ProducerRelation();
            a.Number = 6;
            a.Order = order;

            var b = new ProducerRelation();
            b.Number = 7;
            b.Order = order;

            order.Producers.Add(a);
            order.Producers.Add(b);
            session.Merge(order);
            session.Flush();

只添加了一个孩子。我知道,nhibernate正在“观察”儿童收藏品的变化,但我做错了什么?为什么nhib不能加两个孩子?

SQL:

 NHibernate: SELECT ... WHERE this_.id = ?p0;?p0 = 23
 NHibernate: INSERT INTO gb_avtobus66.ekbprint_producer_relation (producer_price, producer_price_clean, order_id, ekbprint_product_id, client_id, number) VALUES (?p0, ?p1, ?p2, ?p3, ?p4, ?p5);?p0 = 0, ?p1 = 0, ?p2 = 23, ?p3 = NULL, ?p4 = NULL, ?p5 = 6
 NHibernate: SELECT LAST_INSERT_ID()

2 个答案:

答案 0 :(得分:3)

我怀疑是因为您使用的是set集合类型。集合是无序集合,不包含重复项。所以它很可能正在关注这两个新孩子,并认为第二个孩子是重复的。确保重写Equals / GetHashcode以指示什么是重复条目。

答案 1 :(得分:0)

使用get代替Load ....:)