0

I'm looking for a way to stop items from being removed from the many to many table. I found a post stating I could make use of IPostCollectionRemoveEventListener and/or IPostCollectionRecreateEventListener. Problem is that neither of them are being triggered.

Example:

Let's say we have a Table Product and a Table Order. An Order can consist of multiple Products. A product can be sold multiple times (so it's referenced in multiple orders). That's where the many to many Table, ProductOrder, comes into place. All these tables have a column IsDeleted even the many to many.

The many to many table isn't directly mapped in my C# project. I make use of the HasManyToMany.

Mapping of Product:

HasManyToMany(x => x.Orders)
   .ChildKeyColumn("OrderId")
   .AsSet()
   .ParentKeyColumn("ProductId")
   .LazyLoad()
   .Table("ProductOrder")
   .Not.Inverse()
   .Where("IsDeleted != 1");

Mapping of Order:

HasManyToMany(x => x.Products)
   .ChildKeyColumn("ProductId")
   .AsSet()
   .ParentKeyColumn("OrderId")
   .LazyLoad()
   .Table("ProductOrder")
   .Not.Inverse()
   .Where("IsDeleted != 1");

This all works fine, until I delete items from the Products or Orders collection. This causes a full delete while I prefer to use a soft delete by setting the IsDeleted property to 1 but I can't seem to find a way to prevent the delete statement...

Example code of how I delete and save the changes:

var order = ...;
var product= ...;
product.Orders.Remove(order);
...
SessionHandler.CurrentSession.Update(product);
SessionHandler.CurrentSession.Flush();
Beejee
  • 1,836
  • 2
  • 17
  • 31
  • You do not need to call update on the session (given the entities are all attached, meaning they come from a query and not from outside the session). – Stefan Steinegger Jun 23 '16 at 11:27
  • see if this helps http://nhibernate.info/blog/2008/09/06/soft-deletes.html – Ashley John Jun 23 '16 at 11:29
  • I tried out the DefaultDeleteEventListener but it only gets triggered when used on an entity and not on a collection of entities. – Beejee Jun 23 '16 at 11:51

1 Answers1

1

You cannot access DB fields which are not mapped.

Make the relation a regular entity and do not delete it, but set the IsDeleted flag.

Consider also not to filter in in the mapping file but when you access the list on a place where you don't want to see deleted items. It is just more transparent and therefore works smoother.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
  • Don't you think it's kind of dirty to include the table? This means I would have to add it to the mapping by using HasMany ... It also adds extra complexity especially when adding new items (forced to make an instance of the new class ProductOrder). – Beejee Jun 23 '16 at 11:50