0

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

Sreedhar Danturthi
  • 7,119
  • 19
  • 68
  • 111

2 Answers2

1

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.

faester
  • 14,886
  • 5
  • 45
  • 56
  • 1
    may be you want to take a look at this:http://stephenwalther.com/blog/archive/2008/08/20/asp-net-mvc-tip-34-dispose-of-your-datacontext-or-don-t.aspx for dialectic reasons – Sreedhar Danturthi Jun 07 '11 at 08:04
  • @user653622: I see the points; probably I should edit my post to emphasize controlled use of `SubmitChanges` vs just letting the transactions roll back, rather than letting it be a matter of `using` or not. (In the past I have made some bad design where I had a reference to a specific datacontext and then accidentally submitted a transaction that should have been discarded; that's why I'd rather be specific about disposing.) Returning IEnumerable as mentioned in the post is not always my preferred solution, but in these cases disposing the context is of course vital. But thanks for the link – faester Jun 07 '11 at 08:13
1

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

Community
  • 1
  • 1
Pleun
  • 8,856
  • 2
  • 30
  • 50