2011-08-19 6 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 연락처를 추가합니다 : NH 컬렉션에 대한 지속 정보를 잃었을 때

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를 들어 사용 :

일반적인 실수 : 그것은 contact.Customer 관계에 중복이기 때문에 그런데

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

, 당신은, 컬렉션의 역을해야한다 당신의 콜렉션, 가방은 중복을 포함 할 수 있고, 순서를 유지하지 않으며, 백과 함께 개별적으로 SQL을 식별 할 수있는 방법이 없습니다.

NH가 할당 된 모든 엔터티를 제거하고 삽입하는 이유가 여기에 있습니다. 대신 귀하의 요구 사항에 맞는 경우 set을 사용하십시오.

1

는 일반적으로 발생이. 전체 컬렉션을 변경했다고 가정합니다. 데이터베이스를 효율적으로 업데이트하기 위해 하나의 쿼리 (delete ... where customer = 5)의 모든 항목을 제거하고 새 항목을 삽입합니다.

아마 NH에서 제공 한 컬렉션을 반환하지 않습니다.

<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 : 누락 된 역변환을 제외하고는 맵핑이 지금까지는 좋았지 만,이 동작을하지 않아야합니다. –