Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL - Retain DataContext across post-backs?

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.

like image 988
cdonner Avatar asked Feb 27 '26 15:02

cdonner


1 Answers

My suggestion would be to go with your first bullet point there and deserialize/serialize the object and then re-attach it to a new context.

I've used that approach in the past and it has worked well for me. I think you'll run in to less issues and have an easier implementation ahead.

like image 165
Justin Niessner Avatar answered Mar 01 '26 09:03

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!