Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. public T[] Select<T>() {
  2.             if (AttributeExtensions.GetAttribute(typeof(T), out TableAttribute tableAttribute)) {
  3.                 //SELECT * FROM * WHERE
  4.                 MySqlDataReader reader = null;
  5.                 string query = $"SELECT * FROM {tableAttribute.Name};";
  6.                 lock (_db) {
  7.                     using MySqlCommand command = new MySqlCommand() {
  8.                         Connection = _db,
  9.                         CommandText = query
  10.                     };
  11.                     reader = command.ExecuteReader();
  12.                 }
  13.                 if(reader.HasRows) {
  14.                     List<T> elements = new List<T>();
  15.                     while (reader.Read()) {
  16.                         T row = (T) Activator.CreateInstance(typeof(T));
  17.                         typeof(T).GetProperties().ToList().ForEach(property => {
  18.                             try {
  19.                                 if (AttributeExtensions.GetAttribute(typeof(T), out ColumnAttribute columnAttribute)) {
  20.                                     int colunmIndex = reader.GetOrdinal(columnAttribute.Name);
  21.                                     property.SetValue(row, reader.GetValue(colunmIndex));
  22.                                 } else {
  23.                                     int colunmIndex = reader.GetOrdinal(property.Name);
  24.                                     property.SetValue(row, reader.GetValue(colunmIndex));
  25.                                 }
  26.                             } catch {
  27.                                 property.SetValue(row, default);
  28.                             }
  29.                         });
  30.                         elements.Add(row);
  31.                     }
  32.                     return elements.ToArray();
  33.                 } else {
  34.                     return Array.Empty<T>();
  35.                 }
  36.             } else {
  37.                 throw new Exception("There isn't a table - missing TableAttribute");
  38.             }
  39.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement