Convert to List from iDataReader

Here we have demonstrate how we can convert execute reader to list.

First: Check if there is any virtual properties.

public virtual tbl_Product tbl_Product { get; set; }

Second: Reader Property Name should always matches with table column name

public virtual List<T> MapToList<Tentity>(IDataReader reader)
{
    var results = new List<T>();
    var columnCount = reader.FieldCount;
    while (reader.Read())
    {
        var item = Activator.CreateInstance<T>();
        try
        {
            //reader properties
            var rdrProperties = Enumerable.Range(0, columnCount).Select(i => reader.GetName(i)).ToArray();
            foreach (var property in typeof(T).GetProperties())
            {
                //check if property is matched with T Element
                if ((typeof(T).GetProperty(property.Name).GetGetMethod().IsVirtual) || (!rdrProperties.Contains(property.Name)))
                {
                    continue; //if there is properties with virtual or mismatch with reader properties and T Elements
                }
                else
                {
                    if (!reader.IsDBNull(reader.GetOrdinal(property.Name)))
                    {
                        Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                        property.SetValue(item, Convert.ChangeType(reader[property.Name], convertTo), null);
                    }
                }
            }
            results.Add(item);
        }
        catch (Exception e)
        {
            e.ToString();
        }
    }
    return results;
}

Implementation

IEnumerable<T> Results = null;
IDataReader reader = cmd.ExecuteReader();
Results = MapToList<T>(reader).ToList();

Hope this will help you 🙂

Author:

Since March 2011, have 4 years of extensive hands on experience of software development.

Leave a Reply

Your email address will not be published. Required fields are marked *