During a code review I was told to make sure that I do the dispose method for all query objects(LinqToEntities) I use.
Is this such a big memory leak? How can I fix this more elegantly, right now I don’t do any dispose after I’m finished?
My code is the following:
var query = from x in listOfEntities where some_condition select x;
I think this query will not cause memory leak. Its the not the query which may cause the problem. Its probably the data context. Since the data context implements IDisposable you can do:
with
usingclause it will ensure that the connection to the database is closed after the code exits the using statement. It is similar to try/finally block.EDIT:(Based on comments from @Fredrik Mörk). The above code is just to show you the usage of
usingstatement with respect toDataContext. To use thequeryobject outside the using block, you may define it outside theusingblock and callToListor similar method so that you get the execution of the query. Later you can use it. Otherwise due to deferred execution the current code block will fail.