title: Linq to SQL - Retain DataContext across post-backs?
body: <p>I read <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow noreferrer">Rick Strahl's</a> 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. </p>
  
  <p>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".</p>
  
  <p><a href="http://www.west-wind.com/weblog/posts/246222.aspx#246646" rel="nofollow noreferrer">Tom Brune's comment</a> 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, <a href="http://www.west-wind.com/weblog/posts/246222.aspx#247036" rel="nofollow noreferrer">Rick's concerns</a> about this approach are valid, and since my data structures are complex and hierarchical, I don't think I will try this.  </p>
  
  <p>So I am left with few options, as far as I see.</p>
  
  <ul>
  <li>either use Rick's suggestion to deserialize/serialize the object and re-attach it to a new context</li>
  <li>hand-code the logic that compares and updates a fresh copy of the object</li>
  </ul>
  
  <p>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. </p>