Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. public static class DataRecordHelper
  2. {
  3. public static void CreateRecord<T>(IDataRecord record, T myClass)
  4. {
  5. PropertyInfo[] propertyInfos = typeof(T).GetProperties();
  6.  
  7. for (int i = 0; i < record.FieldCount; i++)
  8. {
  9. foreach (PropertyInfo propertyInfo in propertyInfos)
  10. {
  11. if (propertyInfo.Name == record.GetName(i))
  12. {
  13. propertyInfo.SetValue(myClass, Convert.ChangeType(record.GetValue(i), record.GetFieldType(i)), null);
  14. break;
  15. }
  16. }
  17. }
  18. }
  19. }
  20.  
  21. public class Employee
  22. {
  23. public int Id { get; set; }
  24. public string LastName { get; set; }
  25. public DateTime? BirthDate { get; set; }
  26.  
  27. public static IDataReader GetEmployeesReader()
  28. {
  29. SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
  30.  
  31. conn.Open();
  32. using (SqlCommand cmd = new SqlCommand("SELECT EmployeeID As Id, LastName, BirthDate FROM Employees"))
  33. {
  34. cmd.Connection = conn;
  35. return cmd.ExecuteReader(CommandBehavior.CloseConnection);
  36. }
  37. }
  38.  
  39. public static IEnumerable GetEmployees()
  40. {
  41. IDataReader rdr = GetEmployeesReader();
  42. while (rdr.Read())
  43. {
  44. Employee emp = new Employee();
  45. DataRecordHelper.CreateRecord<Employee>(rdr, emp);
  46.  
  47. yield return emp;
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement