C# in Depth

Cover of C# in Depth
Order now (3rd edition)

(You are currently looking at the first edition version of this page. This page is also available for the second and third editions.)

Notes for Chapter 12: LINQ beyond collections

12.1.2: Disposing of DataContexts

In all my examples, I dispose of the DefectModelDataContext after using it. In your code, you may not want to do this - it can be difficult in some cases. Unlike most types which implement IDisposable, DataContext doesn't really need disposing - at least not in most cases. I asked Matt Warren about this design decision, and here was his response:

There are a few reasons we implemented IDisposable:

  • If application logic needs to hold onto an entity beyond when the DataContext is expected to be used or valid you can enforce that contract by calling Dispose. Deferred loaders in that entity will still be referencing the DataContext and will try to use it if any code attempts to navigate the deferred properties. These attempts will fail. Dispose also forces the DataContext to dump its cache of materialized entities so that a single cached entity will not accidentally keep alive all entities materialized through that DataContext, which would otherwise cause what appears to be a memory leak.
  • The logic that automatically closes the DataContext connection can be tricked into leaving the connection open. The DataContext relies on the application code enumerating all results of a query since getting to the end of a resultset triggers the connection to close. If the application uses IEnumerable's MoveNext method instead of a foreach statement in C# or VB, you can exit the enumeration prematurely. If your application experiences problems with connections not closing and you suspect the automatic closing behavior is not working you can use the Dispose pattern as a work around.

12.1.2: Resetting databases: data vs metadata

In section 12.1.2 on page 319, I note two different ways of resetting the database - one issuing direct SQL commands, and the other using LINQ to SQL to load everything and then delete each entry.

It should be noted that although these have the same effect in terms of the data stored directly in the tables, the SQL code (in CleanDatabaseQuickly.cs) also resets some metadata in the table - namely the identity values. This can be important occasionally - e.g. in unit tests which might expect the database to be in an absolutely known state. Most production code shouldn't care what ID values are generated, of course.