Exemple #1
0
        /// <summary>
        /// Takes a data reader and a generic then maps the data to a list of those generics
        /// </summary>
        /// <typeparam name="T">Generic Type to convert the data to</typeparam>
        /// <param name="reader">Data reader to read from</param>
        /// <returns>Returns an IEnumerable</returns>
        public static IEnumerable <T> FromDataTableReader <T>(this DataTableReader reader)
        {   //throw an exception if we get this far without a reader
            if (reader == null)
            {
                throw new InvalidOperationException();
            }
            //get the columns from the data reader (read all fields associated with the reader)
            var cols = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();

            //select each row into a object that represents the data
            return(reader.Select(row =>
            {   //instantiate the generic object
                var obj = Activator.CreateInstance <T>();
                //for each column
                foreach (var col in cols)
                {
                    //get the property of the object where the name matches the data reader (column from the database)
                    var colprop = obj.GetType().GetProperties().SingleOrDefault(p => p.Name == col);
                    //if colprop is not null, then set the value of the object with the given column's value
                    //if you get some sort of error here where it says it can't cast to a specific type, just use CONVERT(type, field) in the sql to cast there
                    colprop?.SetValue(obj, row[col] == DBNull.Value ? null : row[col]);
                } //return the object
                return obj;
            }));
        }