Reputation: 7601
I'm using Data context in my ASP.NET web application.
ComponentDBDataClassesDataContext db = new ComponentDBDataClassesDataContext();
int ifUserExists = (from result in db.Customers where (userName == result.UserName) && (password == result.Password) select result.UserName).Count();
Should I close the data context every time i use it ? If so why should I close it ? If it should not be closed why ?
Can some one give me some elaborate and clear explanation?
Thank you in anticipation
Upvotes: 0
Views: 1455
Reputation: 8920
A lot has been written about this already. In general I advise you to stick to one datacontext for earch unit-of-work. So wrap it in using() everytime you use one.
Have a look here for a nice article: http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management
Or on stackoverflow: When should I dispose of a data context
Upvotes: 1
Reputation: 15086
When you have a DataContext it helps you tracking changes in objects that has been retrieved from its tables or attached to the tables.
So you probably shouldn't close the datacontext every time, but unless you rely on the datacontext to track all you changes - and you have a singletone like instance, you should probably limit the lifetime of each instance by using
the instances and submit/rollback on each operation. Otherwise you will occupy a lot of memory for the track changing.
But I think it is difficult to give a simple yes/no answer to your question.
Upvotes: 1