NHibernate, Logical Deletes and the Second Level Cache, Oh My!

time to read 3 min | 452 words

The comments says it all, I think:

public virtual void Cancel()

{

  /*

  * NHibernate trickery:

  * Position is mapped using where="IsCancelled = 0"

  * When we cancel a Position, we are logically deleting it.

  * This plays havoc with the 2nd level cache, because the Employee.Positions

  * is cached, and the Position with the cached Id can no longer be loaded from the  
  * database.

  * Employee.Positions is mapped using cascade="all" and inverse="true"

  * So, we can remove the Position from the Employee, which will make it work

  * with the 2nd level cache, but because it is mapped as inverse="true", it

  * will not propogate the change to the database, so when we save the Position,

  * its EmployeeId will not be modified.

  */

  IsCancelled = true;

  Employee.Positions.Remove(this);

}