views:

44

answers:

1

I have these classes:

public class User
{
  public IList<Order> LastOrders { get; set;}
}

public class Order {}

Where LastOrders is many-to-many map.

How do I tell (Fluent) NHibernate to remove Order from LastOrders collections for all users when I delete an Order? Is it possible?

That is (db save/load code skipped)

user.LastOrders.Add(order);
Session.Delete(order);
Assert(!user.LastOrders.Contains(order));

Currently I do it manually (lookup for users, update collection, save) before deletion. Without this, NHibernate can't delete Order because it is referenced by users' LastOrders.

A: 

You can safely delete the Order if the collection mapping is set to ignore missing rows.

This will leave orphaned rows in the collection table which will be ignored by NHibernate. These can be cleaned up in some batch process.

HasManyToMany(x => x.LastOrders)
    .NotFound.Ignore();

This will give you faster deletes then your current approach. The disadvantage is that your collection tables will be inconsistent with your model for a time.

Lachlan Roche
Yes but I'll get orphaned records in this case in the many-to-many table?
queen3
OK, still, are you sure that orphaned rows will be ignored by NH? What if it inserts new many-to-many pair with same IDs (assuming it's possible) and then reads back - there will be TWO same results and I'm not sure NH expects this. Anyway, this doesn't look like a clean solution to me.
queen3