Last active
August 29, 2015 14:01
-
-
Save pauliusnorkus/3d094fb5c274f993f094 to your computer and use it in GitHub Desktop.
Helper method to cast SqlDataReader to generic list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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