Linq to SQL Data Source Best Practice

While using linq for SQL in my project, I am currently creating the data context as soon as possible during code execution and deleting it as soon as possible. This causes the data context to be opened and closed many times on the page.

Another option is to open the data class on page load and unload it on the unload page so that the connection is only opened and closed once.

Is there a significant optimization difference between the two, or is one of them a best practice?

My initial thought was that I wanted the connection to open in as little time as possible, but given how fast the page loads, am I spending more time opening and closing those connections than accessing the resource to keep it open?

+1


source to share


2 answers


One thing to consider: the lifetime DataContext

does not affect how long a SQL Server connection is maintained. The SQL statement generated by your Linq To Sql is only executed when evaluating your query.



So when you call (for example),. ToList()

or you call .DataBind()

, the SQL statement is executed. At this time, the connection opens and closes.

+3


source


Behind the scenes, the LinQ to SQL manager uses the IIRC connection pool. So unless you explicitly kill the connection, this shouldn't bother you.



+1


source







All Articles