views:

95

answers:

2

For example, I have 2 methods that use one DataContext (Linq to sql).

 using(DataContext data = new DataContext){
   // doing something
   another_datamethod(data);
 }

 void another_datamethod(DataContext data){
   // doing
 }

Use this style? Or with the same result, I can create separate "using DataContext". What benefits, I would achieve if i'll use one DataContext? Maybe some cache possibilities?

A: 

Datacontexts track changes and do caching, so yes caching is a possibility depending on what work you are performing.

aanund
+1  A: 

Recently, I've read numerous articles and blogs that "highly recommend" that you use multiple DataContexts for your applications, due to multiple issues including the creation of records associated with lookup tables. When I was learning LINQ-to-SQL, one of the most attractive qualities of it for me was the ability to import my complete database schema into one "big" DataContext. So, that's what I did...but a few months, in comes the contradictory information saying that what I did was a bad thing. What to do, what to do...

Nine months later, here's where I stand. My single large DataContext is still my single large DataContext. I have over thirty data repository classes accessing the sixty-plus tables contained within, and I still haven't seen a valid reason to break up my existing data-dom, or to not handle the next project using a single DataContext. The problems that the article and blog writers experienced were valid problems. However, like most things technical, there's never just one way to do things. The best investment of my time and energy was to learn and truly understand how LINQ-to-SQL does what it does. The best book that I found to help me do exactly that is Pro LINQ: Language Integrated Query in C# 2008 by Joseph C. Rattz, Jr. The LINQ-to-SQL coverage is detailed and clear, and there are plenty of examples to clarify the mystery.

So, in your case, create one big DataContext or create many smaller ones...the choice is up to you. Smaller ones clearly give better opportunity for reuse, while one big one helps increase the time you can focus on business logic and presentation code.

Neil T.
I am here speaks not about big, or small. My question was: one instance in all methods of stack or many instances by one in each method.
dynback.com
Sorry for the confusion...If you want to execute multiple methods against the same DataContext, you definitely want to use the using block. Passing in the DataContext as an argument using your example requires that the object be initialized locally for each method call. You could choose to have a single global DC as a singleton object, but that could create concurrency problems if the meta objects aren't flushed after use.The using block assures that the DC instance will be disposed after use. I'd go with that...
Neil T.