C#, Winforms & LINQ to SQL.. Datacontext lifecycle?

By : Ian P
Source: Stackoverflow.com
Question!

We use an enterprise framework that we wrote to facilitate all sorts of company specific stuff that we do.

Within the framework, we provide a LINQ to SQL ORM to use when appropriate. All of this is based on the Microsoft MVC framework. On the MVC side, we new up a datacontext in our base controller. This allows us a full datacontext lifecycle, which is extremely useful for transactions.

One task that we're looking to accomplish is to provide Winforms support.

However, I'm banging my head against the wall trying to figure out an approach that would work in a similar fashion for Winforms.

Given that the MVC approach is pretty straight forward becase one page load represents a logical transaction, it's difficult to come up with a solution on the Winforms side.

Has anyone done anything similar or have any recommendations?

By : Ian P


Answers

I know this thread is a bit old, but in unhaddins we have an implementation of Conversation-per-BusinessTransaction. Currently we have only an implementation for nhibernate, but implementing it for Linq to sql or entity framework should be straightforward. Check my answer in this list.



The problem with only having one datacontext for everything is that you can not have multiple open edits and only commit one. For a lot of application models, this is a non-starter. Therefore, I have one singleton datacontext for reads and create one for each commit action. The update function detaches the objects to be saved from the read datacontext and attaches them to a new commit datacontext, then runs DC.Submit changes.

The only tricky thing is having a way to keep track of if an object should be updated on submit or inserted on submit, and if you have a standard auto num primary key or manage in a collection somewhere what column should serve as the check for which class for insert versus update, this is quite trivial to overcome.



If you are thinking to choose between having a long-lived DataContext (for example as a Singleton in your app) or having short-lived DataContexts, I would choose the second. I would new() a DataContext for each "Unit Of Work" and make sure to keep it alive for as short a period as possible. Creating a new DataContext is not a big issue, since they cache metadata anyway. Having a long lived DataContext gives you a bit of a nightmare when it starts tracking to many objects.



This video can help you solving your question :)
By: admin