Pages

Monday, August 30, 2010

Working with untyped datasets

Example : Working with untyped datasets

DataTable dataTable = new DataTable();
using (var connection = new SqlConnection
(Settings.Default.SkeetySoftDefectsConnectionString))
{
string sql = "SELECT Summary, Status FROM Defect";
new SqlDataAdapter(sql, connection).Fill(dataTable);
}
var query = from defect in dataTable.AsEnumerable()
where defect.Field("Status") != Status.Closed
select defect.Field("Summary");
foreach (string summary in query)
{
Console.WriteLine (summary);
}



Untyped datasets have two problems as far as LINQ is concerned. First, we don’t have
access to the fields within the tables as typed properties; second, the tables themselves
aren’t enumerable. To some extent both are merely a matter of convenience—we
could use direct casts in all the queries, handle DBNull explicitly and so forth, as well as
enumerate the rows in a table using dataTable.Rows.Cast. These
workarounds are quite ugly, which is why the DataTableExtensions and DataRow-
Extensions classes exist.
Code using untyped datasets is never going to be pretty, but using LINQ is far nicer
than filtering and sorting using DataTable.Select. No more escaping, worrying
about date and time formatting, and similar nastiness.
Listing 12.10 gives a simple example. It just fills a single defect table and prints the
summaries of all the defects that don’t have a status of “closed.”

No comments:

Post a Comment