Search code examples
c#partial-classes

Partial Classes and Data Access Code


I have a lot of classes for data-access in one of my projects, but these classes are becoming extremely bulky because of the code that retrieves the data from the data readers.

My code generally looks like this:

// Execute the data reader
using (DbDataReader reader = command.ExecuteReader())
{
  while (reader.Read())
  {
     obj = this.FillDataReader(reader);
     objlist.Add(obj);
  }
}

internal SomeObject FillDataReader(IDataReader dr)
{
   SomeObject obj = new SomeObject ();


   if (!dr.IsDBNull(dr.GetOrdinal("objectID")))
   {
     obj.ID = dr.GetInt32(dr.GetOrdinal("objectID"));
   }

   return obj;
}

Some of the Fill methods easily hit 400+ lines, so is there a decent way to separate these out? Would partial classes be acceptable? In an ideal world, I would be using an ORM, but unfortunately I can't afford the time to learn how to use one.


Solution

  • Certainly you could use partial classes to split away the code for the Fill methods. You could even look at using a template system to generate these partial class files.

    That said, an ORM is a simpler solution and doesn't really take that long to work out if your needs are simple.

    For basic needs where you don't need fine control LINQ to SQL works a treat, and contrary to what many thought it's getting updated as part of VS 2010 / .NET 4.

    Another option is Entity Framework, also being updated as part of VS 2010 / .NET 4. It gives you a lot more control, but also can require a bit more learning.

    How long does it take you to create these 400+ line long Fill methods? Are you sure you couldn't use that time to learn an ORM? No programmer should feel forced to constantly write cookie-cutter code (e.g. ADO.NET Fill methods), it can quickly take the joy out of programming!