Best practice and effective way of using DataContext in Linq to SQL?
At work, Jeff and I have been throwing around ideas to find a best way to implement DataContext in Linq so that we can integrate it into the base class in our framework while achieving following goals.
- Implementation should be easy and non-redundant, so that we do not need to do new DataContext(), every time we have to use one.
- Portability of the DataContext should be such that we do not need to pass it around as parameters from one tier to another.
- “Unit of work” pattern should be well represented and “very” transparent.
- Context should not be persisted without intent, or be open to manipulation from other methods, such that “unit of work” is compromised or a transaction is ill-represented
These seem like simple goals given the features and flexibility of LINQ, however, in reality this has become much more difficult and annoying to achieve than we previously thought. Here are several ideas we have been kicking around, and problem it presents. I would like to hear from people who have effectively used LINQ Datacontext in these scenarios or in a pattern that’s most effective.
1. Creating and disposing LINQ as required.
DbDataContext myContext = new DbDataContext(); //your code goes here myContext.SubmitChanges();Problems with this pattern:- Creating datacontext everytime we need to use is cumbersome and in my opinion just verbose.- If you have to use datacontext in any of the method this code calls, you’ll have to pass the datacontext with it. This is one- too many parameters to pass around
2. Creating a static DataContext and using it throughout the application.
DataLayer.DataContext.Current
Problems with this pattern:- Creating static object isn’t always a good thing. In this case, the context is available for manipulation at any level. And quickly becomes very hard to maintain unit of work - If manipulated by other threads or methods context isn’t clean anymore and cannot be trusted
3. Ambient DataContext – The idea behind ambient datacontext is that context is created for a particular thread or a request (in asp.net) as soon as there is a first call for the DataContext. Then the same context is used for that thread or request unless it is disposed manually. This is done by storing the context in the request/thread data store. The approach to this pattern is similar to static DataContext, however, separation is provided for each thread and requests. This works really well in Asp.Net, however, is again plagued by some of the problems of static context.Problems with this pattern:
Click here to read more...