I have a data access layer namespace that has a lot of repeated code (mostly setting up command objects and executing stored procedures to return data sets that get added to Lists). I'm trying to write a generic factory method that returns a List<T>
. I'm relatively new to both generics and delegates. My thought was to have a Func parameter that creates the objects that get added to the List<T>
. It would be called within the usual while dataReader.Read()
block. My problem is, the data sets I'll be working with have varying numbers of columns.
Here is what I have so far:
private static List<T> ListFromDatabase<T,U>(String CommandName, SqlConnection SqlConn, Func<T,U> CreateListObj,
List<SqlParameter> ParamList = null)
{
List<T> returnList = new List<T>();
using (SqlCommand cmd = new SqlCommand(CommandName,SqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter sp in ParamList)
{
if (sp.Value == null)
sp.Value = DBNull.Value;
cmd.Parameters.Add(sp);
}
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
returnList.Add(CreateListObj);
}
}
return returnList;
}
At my current level of understanding, this may not be possible since I would likely have to vary the Func signature for varying numbers of parameters. Is this do- able, or close? If not I'm open to a different approach, if anyone can help. Many thanks in advance..
Update: This is exactly what I was looking for: