Beispiel #1
0
        public static IEnumerable <T> GetModels <T>(string tableName, DataRequestFilter filter = null) where T : IViewModel
        {
            if (filter is null)
            {
                filter = new DataRequestFilter();
            }

            var result     = new List <T>();
            var conditions = (filter.Conditions != null)
                ? " WHERE " + string.Join(",", filter.Conditions.Select(x => x.Key + " = '" + x.Value + "'")).TrimEnd(',') : string.Empty;

            var reader = client.ExecuteReader
                             (client.Command(string.Format("SELECT * FROM {0}{1}{2}{3}",
                                                           tableName, conditions, $" ORDER BY {filter.OrderColumn} {filter.OrderBy}", $" LIMIT {filter.Limit}")));

            var columns = typeof(T).GetProperties().Select(x => x.Name);
            Dictionary <int, Dictionary <string, object> > results;

            lock (dbLock)
            {
                results = GetResults(reader, columns.ToList());
            }

            foreach (var row in results)
            {
                var values = row.Value.Where
                                 (x => x.Value != DBNull.Value);
                var instance = (T)Activator.CreateInstance(typeof(T));

                foreach (var value in values)
                {
                    var prop = instance.GetType().GetProperties().FirstOrDefault
                                   (x => x.Name == value.Key);

                    // x64 conversion
                    if (prop.PropertyType == typeof(int?))
                    {
                        prop.SetValue(instance, (int?)(long)value.Value);
                    }
                    else if (prop.PropertyType == typeof(int))
                    {
                        prop.SetValue(instance, (int)(long)value.Value);
                    }
                    else
                    {
                        prop.SetValue(instance, value.Value);
                    }
                }

                result.Add(instance);
            }

            return(result);
        }