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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

may be you want to take a look at this:stephenwalther.com/blog/archive/2008/08/20/… for dialectic reasons
@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<T> 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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.