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 MapToList(IDataReader reader)
{
    var results = new List();
    var columnCount = reader.FieldCount;
    while (reader.Read())
    {
        var item = Activator.CreateInstance();
        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 Results = null;
IDataReader reader = cmd.ExecuteReader();
Results = MapToList(reader).ToList();

Hope this will help you 🙂

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply