views:

28

answers:

1

Dearest All,

I've got a many-to-many association between Lists and ListItems: a List knows about its Items, but a ListItem doesn't know about the containing lists. The cascade is saveupdate.

So, whenever I'm trying to delete a ListItem entity, I'm getting an SQLException saying I'm breaking the referential integrity. NHibernate tries to delete my ListItem without deleting the corresponding row in the linking table. The question is, is it possible to instruct NHibernate to delete my ListItem without breaking the referential integrity?

In case I have to manually remove the item from all containing lists, how do I properly do that?

Thanks a lot for any advice.

ulu

A: 

You need to set the mapping on the child to inverse=true. From another thread:

When you call SaveOrUpdate NHibernate first deletes all of the child objects. Then, because neither relationship is marked as inverse, NHibernate also tries to set the foreign key column in your child table to null. Since the rows have already been deleted, you receive the second error. You need to set inverse=true on one side of your relationship to fix this. This is usually done on the one (primary key or parent) side. If you do not do this, NHibernate will make the appropriate updates for each side of the relationship.

public class StoreMap : ClassMap<Store>
{
  public StoreMap()
  {
    Id(x => x.Id);
    Map(x => x.Name);
    HasMany(x => x.Staff)
      .Inverse()         // Magic code!
      .Cascade.All();
  }
}
Rafael Belliard
Fantastic, thanks!!!
ulu
However, now adding to a list doesn't work!!! The item itself is saved to the database, but I cannot add it to the list. I'm using list.Items.Add(newItem); _session.Save(newItem); _session.Update(list);
ulu
How does adding to the list **not** work? If you need to, update your question so we have more details. :)
Rafael Belliard