1 How does it work? How does the remote DataContext still query the database for results after placing the DataContext?
It does not work . There you are not showing us something. I assume that either your repository class does not manage the DataContext properly / at the right time, or that you randomly write ToList() at the end of each request, which completely negates the conversion of the request and you usually get deferred execution.
Try using the following code in a test application, I guarantee that it will throw an ObjectDisposedException :
// Bad code; do not use, will throw exception. IEnumerable<Person> people; using (var context = new TestDataContext()) { people = context.Person; } foreach (Person p in people) { Console.WriteLine(p.ID); }
This is the easiest reproducible event possible, and it will always throw. On the other hand, if you write people = context.Person.ToList() instead, then the query results are already listed inside the using block that I put on, this is what happens in your case.
2 What does Dispose () actually do?
Among other things, it sets a flag indicating that a DataContext is located, which is checked at each subsequent request, and raises a DataContext to throw an ObjectDisposedException with the message Object name: 'DataContext accessed after Dispose.'.
It also closes the connection if the DataContext opened it and left it open.
3 I heard that there is no need (for example, to see this question) to get rid of the DataContext, but I got the impression that this is not a bad idea. Is there a reason not to get rid of the DataContext LinqToSql?
Dispose DataContext required , since it is necessary to Dispose each other IDisposable . You can potentially leak connections if you do not delete the DataContext . You can also skip memory if any of the objects obtained from the DataContext are kept alive, because the context supports an internal cache identifier for the unit of work template it implements. But even if it is not, you donβt have to worry about what the Dispose method does internally. Suppose he is doing something important.
IDisposable is a contract that states: "cleaning may not be automatic, you need to spare me when you are done." You have no guarantee that the object has its own finalizer, which will clear after you if you forget Dispose . Implementations are subject to change, so you should not rely on the observed behavior, and not on explicit specifications.
The worst thing that can happen if you choose IDisposable with an empty Dispose method is that you spend several processor cycles. The worst thing that can happen if you do not remove IDisposable with a non-trivial implementation is a resource leak. The choice is obvious; if you see IDisposable , do not forget to delete it.