C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).
Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.
brings, at page 376, a discussion on disposing DataContext
/ObjectContext
instances.
Disposing DataContext/ObjectContext
Although DataContext/ObjectContext implement IDisposable, you can (in general) get away without disposing instances. Disposing forces the context’s connection to dispose—but this is usually unnecessary because L2S and EF close connections automatically whenever you finish retrieving results from a query. Disposing a context can actually be problematic because of lazy evaluation. Consider the following:
IQueryable<Customer> GetCustomers (string prefix) { using (var dc = new NutshellContext ("connection string")) return dc.GetTable<Customer>() .Where (c => c.Name.StartsWith (prefix)); } ... foreach (Customer c in GetCustomers ("a")) Console.WriteLine (c.Name);
This will fail because the query is evaluated when we enumerate it—which is after disposing its DataContext.
There are some caveats, though, on not disposing contexts.
(and it goes on to list them...)
At the end, to avoid the exception just described, it states:
If you want to explicitly dispose contexts, you must pass a
DataContext/ObjectContext
instance into methods such asGetCustomers
to avoid the problem described.
The question:
I do not get what the author meant. (no example followed).
I mean, does the author's says you can have the method still return an IQueryable<Customer>
, dispose of the DataContext
parameter and keep deferred execution
altogether ?
How is this achieved ? I can see it happening only if giving up lazy loading.