tags:

views:

107

answers:

2

Hi, this is a simple question that you might find out if you have been in this situation before:

Imagine that I have a loop and inside it I create an instance of a DataContext and I perform some queries to the database.

The question is... Is the DataContext opening a Connection only the first time and reusing it or a new connection to the DB is open/closed in every loop? If the latter, can I force in some way to use only one connection?

thx

+1  A: 

Are you disposing of the DataContext on every iteration (i.e., are you creating the datacontext with a "using" statement?). If so, then you will be opening and closing the connection every time. Otherwise, it would depend on your code I guess - if you've got a private variable that goes in and out of scope on each loop, then it would be the same effect.

Why can't you just create one DataContext outside of the loop and use it? This is the recommended practice for repository classes.

womp
The idea was using the "using" statement for every loop
despart
So that pretty much answers your question ;)
womp
A: 

How about:

 using(var dc=new FooDataContext())
 {
     for(var i=0;i<someVal;++i)
     {
         dc.SomeTable.Where.....
     }
 }
spender
This is how i have it right now but i perform some updates (see my comment in the question)... Maybe i just have to figure out how to avoid that exception...
despart