Search code examples
castle-activerecordcastleonupdate

Why Castle Active Record's `FindAllByProperty` calls `OnUpdate`?


When I call FindAllByProperty it calls OnUpdate in castle Active Record, This causes an stack overflow because I do some duplicating check on OnUpdate an instance. Consider following code. Why it calls OnUpdate? How can stop it?

protected override void OnUpdate()
{
    if (FindAllByProperty("Title", this.Title).Length > 1)
        throw new Exception("duplicate Message in update");

    base.OnUpdate();
}

Solution

  • Here's what's probably happening:

    1. Something in your app flushes your session.
    2. While flushing, NHibernate / ActiveRecord executes your OnUpdate()
    3. OnUpdate() calls FindAllByProperty()
    4. FindAllByProperty() tries to run a query within the same session, but the session is still dirty, so NHibernate flushes the session.
    5. Back to 2.

    Thus, a stack overflow.

    To avoid this, try running FindAllByProperty() within a new session:

    using (new SessionScope())
      if (FindAllByProperty("Title", this.Title).Length > 1)
         throw new Exception("duplicate Message in update");