I read Rick Strahl's post about DataContext lifetime management, and some of the other related questions on Stackoverflow. If they contained an answer to my question, I must have missed it.
I generally follow the atomic approach and instantiate a DataContext for a unit of work when it is needed, and dispose it afterwards. This worked well until I hit a scenario with a complex page that contains a multi-view control with several grids and popup panels that all represent one unit of work. The data is in memory (I actually stuff the root object into the session so that the entire hierarchy is available across post-backs). Obviously, the DataContext is long gone by the time the user clicks on "Save".
Tom Brune's comment caught my eye at first, because it seemed like such an elegant approach - to use reflection to "wet" a fresh copy of the object and to update the database using a new DataContext. However, Rick's concerns about this approach are valid, and since my data structures are complex and hierarchical, I don't think I will try this.
So I am left with few options, as far as I see.
- either use Rick's suggestion to deserialize/serialize the object and re-attach it to a new context
- hand-code the logic that compares and updates a fresh copy of the object
Which one should I follow, and is there a third option, i.e. can I keep the DataContext around between post-backs? If that's feasible, it would require the least amount of coding, as my root object has about a dozen children.