简体   繁体   中英

Nhibernate Many to Many Soft Delete

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM