views:

61

answers:

2

Sorry, if this is a duplicate. Please point me to the appropriate question if this is but I could not find exactly what I am looking for.

So I am using a Linq to SQL datacontext for entity tracking and persistence in an ASP.NET web application. It is for an Intranet application that does not have a ton of users at a time. Right now I cam storing the datacontext in session state, which makes me feel dirty! It seems like I need the context always to be present though because I need to preserve the change tracking on the entities that are being modified. All of our screens have a Save button that would then call SubmitChanges() on the DataContext and persist all of the pending changes in memory.

Should I be storing the DataContext? Should I be disposing of it at the end of each request and then recreate it somehow and get the pending changes? If I should recreate it every time, I dont understand how the context could know what has changed without a ton of redundant database hits on each request.

+3  A: 

First, I would say to stop putting things in Session altogether. Especially if you don't have a lot of users, just load the data when you need it.

Don't store the data context at all. Just create a new one on each page when you need it. When they hit the Save button, recreate a data context, load the object from the database, make the changes necessary based on the form input, and then save it back to the database. It should just be two database hits for each object, one to load, and then one to save it back.

Mike Mooney
I want to give both you and tv the correct answer checkbox... you were first though!
Rob Packwood
+2  A: 

I think the best practice with the data context is the Unit of Work pattern, where the scope of the Unit of Work is the single request that you are servicing. Instantiate a new data context each time you need to make changes. If you're concerned about overwriting changes that have been made after drawing the previous page, then consider using and persisting a version/timestamp in a hidden field and checking it against that returned from the data context when retrieving the entity to update.

tvanfosson
Maybe I don't fully understand the Unit of Work pattern, but isn't the gist of it to stick around and keep track of all Added, Updated, and Deleted entities? So how is the DataContext accomplishing that if I am rebuilding it up during each time I make changes?
Rob Packwood
In the context of a web request, the unit of work would apply to a single request -- not span requests. Obtain the data for the request, make any changes/insert/deletions to service the request, then dispose of the context. I'll clarify my answer.
tvanfosson
Unit of Work is like a transaction - create your unit of work, pass the reference to the repositories that are using, then call the appropriate "Commit" once you are finished. Linq2SQL supports the concept natively, as it tracks all your changes ...
TobyEvans