Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. namespace Test
  2. {
  3. public class Contract
  4. {
  5. public uint Id { get; set; }
  6. public string Number { get; set; }
  7. public DateTime DateStart { get; set; }
  8. }
  9.  
  10. public class GenericObj
  11. {
  12. public Dictionary<string, object> PropertiesNameValueCollection { get; set; } = new Dictionary<string, object>();
  13. }
  14.  
  15. public class MySqlService
  16. {
  17. private string ConStr;
  18. public MySqlService(string conStr)
  19. {
  20. ConStr = conStr;
  21. }
  22.  
  23. public List<GenericObj> ExecuteReader(string sql)
  24. {
  25. var list = new List<GenericObj>();
  26. using (var con = new MySqlConnection(ConStr))
  27. using (var cmd = new MySqlCommand(sql, con))
  28. {
  29. con.Open();
  30. var reader = cmd.ExecuteReader();
  31. while (reader.Read())
  32. {
  33. var count = reader.FieldCount;
  34. var obj = new GenericObj();
  35. for (int i = 0; i < count; i++)
  36. {
  37. obj.PropertiesNameValueCollection.Add(reader.GetName(i), reader.GetValue(i));
  38. }
  39. list.Add(obj);
  40. }
  41. }
  42. return list;
  43. }
  44. }
  45.  
  46. public class Resolver<T>
  47. {
  48. public T Resolve(GenericObj obj)
  49. {
  50. var type = typeof(T);
  51. T specificObj = (T)Activator.CreateInstance(type);
  52. foreach(var field in obj.PropertiesNameValueCollection)
  53. {
  54. type.GetProperty(field.Key).SetValue(specificObj, field.Value);
  55. }
  56. return specificObj;
  57. }
  58. }
  59.  
  60. class Program
  61. {
  62. static void Main(string[] args)
  63. {
  64. var service = new MySqlService("constr");
  65. var result = service.ExecuteReader("SELECT mai_id as Id, mai_no_d as Number, mai_date_start as DateStart FROM main");
  66.  
  67. var list = new List<Contract>();
  68. var resolver = new Resolver<Contract>();
  69. foreach (var genObj in result)
  70. {
  71. list.Add(resolver.Resolve(genObj));
  72. }
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement