Creating history objects within the Persisting() and/or Updating() methods

Jul 1, 2013 at 11:16 AM
Edited Jul 1, 2013 at 11:18 AM
I have a class Foo which has a History collection of type FooHistory - a simple object that just captures the state of various fields when the object is changed, created within the Peristing() and Updating() methods. This is a simple and common requirement. However, it is quite easy to end up with a StackOverflow error. I therefore offer the following guidelines:
  1. If you create a FooHistory object within the Persisting() method on Foo, do not explicitly persist that FooHistory object. Rather, just create it transiently, and add into the History collection. EF will take care of persisting the whole graph i.e. the Foo and any transient FooHistories in the History collection in one go. It is not sufficient to ensure that the FooHistory's Foo property points to 'this'.
  2. If creating a FooHistory object within the Updating() method (intended to capture any updates to Foo after persisting) then you do need to call Container.Persist(..) on the new FooHistory object and before adding it to the History collection. Alternatively, in this case you may just set the Foo property on the FooHistory to 'this' and then persist it.
(see also As a temporary workaround to avoid getting two FooHistory objects when Foo is persisted, you can just build a check into the Updating() method and only create a new FooHistory if Foo is in fact already persisted.)