1

I have just started using the Data Access Application Block from microsoft. There are very few instructions on the correct way to use the library. Just wanted to know if this is the correct way to use the data reader.

SqlDataReader reader = SqlHelper.ExecuteReader(config.ConnectionString, CommandType.Text, "select * from category");
List<string> a = new List<string>();
using (reader)
{
     while (reader.Read())
     {
          string t = reader.GetString(1);
          a.Add(t);
     }

     return a;
}

will everything get closed doing it this way? Is there any chance of memory leaks?

Luke101
  • 63,072
  • 85
  • 231
  • 359
  • The latest release (v6) on CodePlex now has some very well written documentation, explanations and sample code. See http://entlib.codeplex.com/releases and in particular the "Developer’s Guide to Microsoft Enterprise Library" which can be downloaded as a pdf and explains DAAB usage and rationale very well. – mdisibio Aug 31 '13 at 06:07

2 Answers2

2

Put your reader initialization into the using block, and I would avoid using column numbers if you can, as they essentially turn into magic numbers. Unfortunately, that just requires you use the column names, but I have found that column names are less likely to change than column offsets, and you can always put your column names in a configuration file or something. Also, make sure you take into account the possibility for null columns

using(var reader = SqlHelper.ExecuteReader(etc. etc. etc.))
{
    while(reader.read()){
    {
        //Only need to do this if you don't want your string to be null
        //and if the "columnName" column is nullable.
        var stringValue = reader.IsDBNull(reader.GetOrdinal("columnName") 
                        ? "" 
                        : reader.GetString(reader.GetOrdinal("columnName"));
        a.Add(stringValue);
    }
}
AJ.
  • 16,368
  • 20
  • 95
  • 150
0

HAve a look at

The Enterprise Library Data Access Application Block, Part 2

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284