Skip to content

Instantly share code, notes, and snippets.

@pauliusnorkus
Last active August 29, 2015 14:01
Show Gist options
  • Save pauliusnorkus/3d094fb5c274f993f094 to your computer and use it in GitHub Desktop.
Save pauliusnorkus/3d094fb5c274f993f094 to your computer and use it in GitHub Desktop.
Helper method to cast SqlDataReader to generic list
public static class SqlHelpers
{
public static List<T> ToList<T>(this SqlDataReader reader)
{
var properties = typeof(T).GetProperties().Select(x => x.Name);
List<T> result = new List<T>();
while(reader.Read())
{
var instance = Activator.CreateInstance<T>();
foreach(var p in properties)
{
var prop = instance.GetType().GetProperty(p);
var value = (reader[p] == DBNull.Value) ? null : reader[p];
prop.SetValue(instance, value, null);
}
result.Add(instance);
}
reader.Close();
return result;
}
}
using(var connection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]))
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Posts", connection);
List<Post> posts = cmd.ExecuteReader().ToList<Post>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment