tags:

views:

200

answers:

1

Hi,

I read http://stackoverflow.com/questions/226127/multiple-single-instance-of-linq-to-sql-datacontext and http://www.west-wind.com/weblog/posts/246222.aspx

I'm developing a web application. In my blclass that has many methods that do some query against the DB, in each and every method, I declare :

Dim db As New DemoDataClassesDataContext

to create an new instance of DataContext for every transaction. I'm wondering if this will become a problem with performance or any other problems that I'm not aware of. Is this the right way to do it ?

Should I use :

Dim db As New DemoDataClassesDataContext or Using db As New DemoDataClassesDataContext

I understand that all objects in .NET are eventually disposed automatically by the automatic garbage collector.

The using statement is to dispose of the object once the code between the statement has run.

In this blog post http://lee.hdgreetings.com/2008/06/linq-datacontex.html says that "It is generally not critical to call Dispose on Datacontext."

I have no clear picture yet on how to manage the LINQ datacontext liftime for the web application. Any suggestion is much appreciated.

Thank you.

A: 

The using statement is to dispose of the object once the code between the statement has run.

This is incorrect. The using will call finally on the object when the code exits the using scope. This will in turn call close on the underlying database connection. Thus you need the using statement to make sure the database connection is closed.

EDIT:

You don't actually have to call dispose on a datacontract as long as you enumerate the entire result set as discussed here: http://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context

Jonathan Parker
LINQ data contexts don't (usually) keep open connections. See http://stackoverflow.com/questions/389822/when-should-i-dispose-of-a-data-context - and in particular the part where I quote Matt Warren.
Jon Skeet
Hah, you learn something every day. I guess the use of disposable is disposable in this case.
Jonathan Parker