2011-08-19 60 views
1

客户可以有多个联系人。下面的代码正在工作,但...此客户的联系人将首先被删除,然后再次插入。是不可能避免这种删除,只需插入新的?NHibernate:多对多集合

<class name="Customer" table="Customer"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <property name="LastName" not-null="true" /> 

    <bag name="Contacts" cascade="all-delete-orphan" table="CustomerContact"> 
     <key column="Customer" not-null="true" /> 
     <many-to-many class="Contact"/> 
    </bag>l 
</class> 

<class name="Contact" table="Contact"> 
    <id name="Id"> 
     <generator class="native" /> 
    </id> 
    <property name="LastName" not-null="true" /> 

    <many-to-one name="Customer" column="Customer" not-null="true" /> 
</class> 

public virtual void AddContact(Contact contact) 
{ 
    Contacts.Add(contact); 
    contact.Customer = this; 
} 

当我做这个代码两次,加2个联系人:

Contact contact = new Contact() { LastName = "MyLastName" }; 
Customer customer = session.Get(customerId); 
customer.AddContact(contact); 
session.Update(customer); 

enter image description here

+0

更改后不需要致电更新(客户)。它在会话中会自动更新。 –

+0

联系人如何实施? –

回答

2

您正在使用的bag你的收藏,一个包可以包含重复项,不维护顺序,并且没有办法用SQL明确识别包中的单个条目。

这就是NH删除并插入所有分配的实体的原因。如果它符合您的要求,请使用set

1

这种情况通常发生在新罕布什尔州损失了约集合持续性信息。它假定你改变了整个集合。为了高效地更新数据库,它将删除一个查询中的所有项目(删除...,其中customer = 5)并插入新项目。

您可能不会返回NH提供的集合。

典型错误:

IList<Contact> Contacts 
    { 
    get { return contacts; } 
    // wrong: creates a new List and replaces the NH persistent collection 
    set { contacts = value.ToList(); } 
    } 

顺便说一句,你应该收集逆,因为它是一个冗余的contact.Customer关系:

<bag name="Contacts" cascade="all-delete-orphan" table="CustomerContact" inverse="true"> 
    <key column="Customer" not-null="true" /> 
    <many-to-many class="Contact"/> 
</bag> 
+0

这不是更麻烦的映射吗? –

+0

@Kris:到目前为止映射看起来不错,除了缺少的逆,它不应该导致这种行为。 –