Reputation: 11780
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
Upvotes: 0
Views: 350
Reputation: 120380
How about:
using(var dc=new FooDataContext())
{
for(var i=0;i<someVal;++i)
{
dc.SomeTable.Where.....
}
}
Upvotes: 0
Reputation: 116977
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.
Upvotes: 1