Luke Smith Write today, wrong tomorrow

Creating a generic list from a SqlDataReader

I've just been working on the data access layer for a project at work and found myself
replicating alot of very similar code when it came to looping through the SqlDataReader
and creating and populating a custom object for each IDataRecord (creating lists of
projects, staff etc). I sat back and thought "there must be an easier way to write
not much code, after all this is the world of .NET and C#".

So here's my solution for returning a a generic List<> populated from a SqlDataReader.

public interface IObjectPopulator
{
object Populate(IDataRecord
dr);
}

public class Project
: IObjectPopulator
{
   private int?
_id;
   public int?
Id
   {
      get { return _id;
}
      internal set
{ _id = value;
}
   }

   private string _name;
   public string Name
   {
      get { return _name;
}
      set { _name = value;
}
   }

   #region IObjectPopulator
Members

   public object Populate(IDataRecord
dr)
   {
      Project project = new Project();
      project.Id = Convert.ToInt32(dr["project_ID"]);
      project.Name = Convert.ToString(dr["project_name"]);

      return project;

   }

   #endregion

}

protected List<T>
PopulateList<T>(SqlDataReader reader)
{
   ArgumentValidator.CheckForNullReference(reader, "reader");
   List<T> list = null;

   try

   {
      list = new List<T>();

      while (reader.Read())
      {
         object o = Activator.CreateInstance(typeof(T));
         IObjectPopulator populator = o as IObjectPopulator;

         if (populator
!= null)
         {
            T item = (T)populator.Populate(reader);

            list.Add(item);
         }
      }
   }
   finally

   {
      reader.Close();
   }

   return list;
}

Now
instead of having to loop thru the SqlDataReader in every method that creates a List<> I
can just call

   List<Project>
projects = base.PopulateList<Project>(reader);

Saving
myself alot of lines of code.

comments powered by Disqus