1

I have a object Customer, this object has an ISet list of Contact. When I delete a Customer I'd like to delete the Contact.

I use the mapping below, I tried all option in cascade but still have this problem : The DELETE statement conflicted with the REFERENCE constraint "FK4FF8F4B29499D0A4". The conflict occurred in database "MyDB", table "dbo.Contact", column 'Customer'.

The mapping Customer

<set name="Contacts" table="CustomerContact" cascade="save-update">
    <key column="Customer" />
    <many-to-many class="Contact" column="Contact" />
</set>

The mapping Contact

<many-to-one name="Customer" column="Customer" not-null="true" />
TheBoubou
  • 19,487
  • 54
  • 148
  • 236
  • my guess was to set all-delete-orphan, but it seems you already tried that. Try looking at this answer http://stackoverflow.com/questions/302720/how-to-delete-child-object-in-nhibernate/302860#302860. – Iridio Aug 27 '11 at 09:35

2 Answers2

3

It is strange that you have bidirectional association between customer and contact mapped like that. If Customer can be associated with multiple Contacts, and vice versa, you should have many-to-many on both sides. But you have many-to-one at Contact side. And you mention that you want to cascade deletes to Contact.

Perhaps you should consider mapping Contacts collections as one-to-many? Try this for Customer mapping, note inverse attribute.

<set name="Contacts" 
     table="CustomerContact" 
     inverse="true" 
     cascade="all-delete-orphan" >

    <key column="Customer" />
    <one-to-many class="Contact" />
</set>

With this Contact mapping:

<many-to-one name="Customer" column="Customer" />

You will also have to 'chase the pointers': null out Customer.Contact when corresponding Contact is removed from Customer.Contacts collection.

Dmitry
  • 17,078
  • 2
  • 44
  • 70
  • Thanks Dmitry working 100% :) Sometimes it's not easy to understand all properties (inversion, ...) in NHibernate – TheBoubou Aug 27 '11 at 18:52
0

having the two propeties

 inverse="true" 

and

 cascade="all-delete-orphan" 

is the key..

apart from this you can as well do this while deleting the customer object:

customer.Contacts.Clear();
Session.Delete(customer);
Baz1nga
  • 15,485
  • 3
  • 35
  • 61