tags:

views:

34

answers:

1

I have some problems with deleting object. I am getting the following error:

[Test.Item#ab9a9869-b2c1-4262-8d33-9dd9010abd96][SQL: DELETE FROM InvoerItem WHERE DbId = ? AND Version = ?]

The DELETE statement conflicted with the REFERENCE constraint "FK9100B9F130A0A610". The conflict occurred in database "", table "dbo.InvoerItemToInvoerItem", column 'Listener_id'.

The situation is like this i have an object that has a collection of references to other objects of the same kind these are called listerners.

The mapping for the object looks like this :

public InvoerItemMap()
{
    HasManyToMany(x => x.Listeners)
        .ChildKeyColumn("Listener_id")
        .Cascade.None()
        .Access.CamelCaseField(Prefix.Underscore);
}

What is it that causes the exception when deleting an object that has a listeners connected to it? Do I have to inverse the relation ship of the listeners?

A: 

No, inverse doesn't help.

you need to specify what you want to do with the listeners. There are basically two options:

  • tell the user that there are listeners around and he can't delete this object
  • unregister the listeners by the software.

If you decide to unregister the listeners, then ... just implement it.

InvoerItem itemToDelete = ...;
itemToDelete.Listeners.Clear();
session.Delete(itemToDelete);

It would be even better to let the entity manage the listeners:

itemToDelete.UnregisterListeners();

Edit: if you have references from the listeners to the invoerItems, you need to remove them as well:

public void UnregisterListeners()
{
    foreach(Listener listener in Listeners)
    {
        listener.Invoeritem = null;
    }
    Listeners.Clear();
}

By the way: in this case you should make the listeners inverse. Don't forget to map it to the same foreign key.

Stefan Steinegger
Thank you for your commentI did the above but i still get the same error. I have added a method called Unregister and there i clear the list. Do i have to ajust the mapping or something ?
Wombat
Are there references from the listeners to the InvoerItems? Then you need to remove them as well.
Stefan Steinegger
There exists a circular reference. But i cant delete it because then i get a stackoverflow exception.
Wombat
Then it is not an NH related problem I guess. You should be able to fix it just by implementing the classes correctly. If you need further advise there, ask another question which is not NH related (if so).
Stefan Steinegger