Guest User

Untitled

a guest
Aug 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. Mapping SqlDataReader results to classes
  2. public static Listing Get(SqlConnection connection,int listingId)
  3. {
  4. Listing listing = null;
  5. SqlDataReader reader = null;
  6. try
  7. {
  8. SqlCommand cmd = Global.GetSQLCommand("[Listing].[GetDetails]", connection);
  9. Global.AddIntParameter(cmd, "@pListingId", listingId);
  10.  
  11. reader = cmd.ExecuteReader();
  12.  
  13. var colDictionary = Global.GetColumnsInReader(reader);
  14.  
  15. while (reader.Read())
  16. {
  17. listing = new Listing(reader,colDictionary);
  18. }
  19. }
  20. catch (Exception e)
  21. {
  22. Global.HandleException(e);
  23. }
  24. finally
  25. {
  26. Global.DestroyReader(reader);
  27. }
  28. return listing;
  29. }
  30.  
  31. SqlCommand cmd = Global.GetSQLCommand("[Listing].[GetDetails]", connection);
  32. Global.AddIntParameter(cmd, "@pListingId", listingId);
  33. reader = cmd.ExecuteReader();
  34.  
  35. public static Dictionary<String,Int32> GetColumnsInReader(SqlDataReader reader)
  36. {
  37. Dictionary<String, Int32> columns = new Dictionary<String, Int32>();
  38. for (int i = 0; i < reader.FieldCount; i++)
  39. {
  40. String columnName = reader.GetName(i);
  41. int columnIndex = reader.GetOrdinal(columnName);
  42. columns.Add(columnName, columnIndex);
  43. }
  44.  
  45. return columns;
  46. }
  47.  
  48. var colDictionary = Global.GetColumnsInReader(reader);
  49.  
  50. while (reader.Read())
  51. {
  52. listing = new Listing(reader,colDictionary);
  53. }
  54.  
  55. public Listing(SqlDataReader reader, Dictionary<String, Int32> colDictionary)
  56. : base(reader, colDictionary, "ListingId")
  57. {
  58. _comment = Global.GetStringData(reader,colDictionary, "Comment");
  59. _description = Global.GetStringData(reader,colDictionary,"Description");
  60. _detailViewCount = Global.GetIntData(reader, colDictionary, "DetailViewCount");
  61. _vehicle = new Vehicle(reader, colDictionary);
  62. }
  63.  
  64. public static String GetStringData(SqlDataReader reader, Dictionary<String, Int32>
  65. colDictionary, String columnName)
  66. {
  67. int columnIndex = 0;
  68.  
  69. if (colDictionary.TryGetValue(columnName, out columnIndex))
  70. {
  71. if (reader.IsDBNull(columnIndex))
  72. return "";
  73.  
  74. var test = reader.GetValue(columnIndex);
  75. return Convert.ToString(test);
  76. }
  77.  
  78. return null;
  79. }
Add Comment
Please, Sign In to add comment