Menu Close

Month: April 2011

Different approach to reading data from SqlDataReader [source code included]

When reading data from SqlDataReader you have to know your select statement’s columns order to read and map data from database to your model. Often it looks somehow like this:

using (SqlDataReader reader = command.ExecuteReader())
{
	if (reader.Read())
		return new AnimalModel
		{
			AnimalId = reader.GetInt32(0),//or better with enum like that: AnimalId = reader.GetInt32((int)AnimalSelect.AnimalId)
			BirthDate = reader.GetDateTime(1),
			Name = reader.GetString(2)
			//etc...
		};
	else return null;
}

It’s a good practice to create enum representing select’s columns and using it instead of int indexes.
But wouldn’t it be better if you could just do it like that:

using (SqlDataReader reader = command.ExecuteReader())
{
	if (reader.Read())
		return reader.ReadObject();
	else return null;
}