nhibernatehibernatecascadenhibernate-cascadehibernate-cascade

nhibernate (or hibernate) Conditional cascading


I have a class User, that has a property Event, which has many Sessions. Basically, a user register to an event which have many sessions hours.

The user can register for an event, but the sessions hours are purely informative.

But when I write a user to the database with NH, it updates the sessions hours too. How can I prevent that, knowing that I still need the sessions hours to be inserted/updated when I create/update an event.


Solution

  • This might not totally apply to your question, but I've had issues where I wanted to conditionally cascade deletes based on certain business rules.

    A lot of the times, you can handle this in your persistence logic. I had a case where I went with NHibernate Event Listeners.

    public class ConditionalDeleter: IPostDeleteEventListener
        {
            public void OnPostDelete(PostDeleteEvent @event)
            {
                var foo = @event.Entity as Foo;
                if (foo != null)
                {
                    if (foo.ShouldDeleteBar)
                    {
                        ISession session = @event.Session.GetSession(EntityMode.Poco);
                        session.Delete(foo.Bar);
    
                        session.Flush(); 
                    }
                }
            }
        }