NHibernate. Can't add two child to parent
I have common parent\children scenario:
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; }
}
Mappings:
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>
....
When I run this code:
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();
only one of my children is added. I know, that nhibernate is "watching" the child collection for changes, but what I do wrong? Why nhib can't add two children?
SQL:
NHibernate: SELECT ... WHERE this_.id = ?p0;?p0 = 2开发者_Python百科3
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()
I suspect it is because of the fact that you're using a set
collection type. A set is an unordered collection that contains no duplicates. So likely it's looking at the two new children and thinks that the second one is a duplicate. Make sure you override Equals/GetHashcode to indicate what is a duplicate entry.
Use get instead of Load.... :)
精彩评论