Reputation: 12423
Is it better to create it once and leave it there, re-using it (possibly from a static property) or to create it new on every access to the DB?
Upvotes: 0
Views: 1031
Reputation: 7203
I would also add, that the way you treat your DataContext would depend on
a. The nature of your application.
b. Business requirements.
So if you are developing a Web App with IIS or any other web server supported with .net, it is better to use a new instance of DataContext for each Unit Of Work (atomic operation) due to the nature of the processing model associated with this case of thin client development.
However, if your App runs in the proccess that is highly controllable as far as execution and state of it (WinForms, WPF), and you want to have your datacontext operate in the context of a UserSession (One Single DataContext per User per Session), you can tie the creation of it with when the application starts up and dispose of it when application is about to be unloaded. You can also take a look at using the Singleton pattern for that.
Upvotes: 0
Reputation: 18237
Create a new one for each access to the database. Also put it in a using statement:
using (var db = new MyDatabase())
{
// do query
}
Upvotes: 1
Reputation: 42334
There are a few duplicates of this question (look in the right hand of this page) - and I would surprised if it does not get closed as a result.
For my part I 'll refer you to an answer I gave to another question, in which I cover L2S lifetimes.
How linq to sql works with sql connections?
Upvotes: 0
Reputation: 245389
It is typically considered a best practice to use the Unit Of Work pattern when working with an Entity (or LINQ to SQL) context.
That is usually fairly simple since the context wraps up all the difficult work. All you have to do is:
Create the context.
Perform all operations that constitute a single Unit of Work.
Commit the changes (if necessary). You can roll back if there is an error.
Dispose of the context.
Upvotes: 1