Dynamic Mapping Database result to Entity T

Introduction

  • Dynamic Mapping the result from SQL, Columns to C# Properties.
  • This uses mapping of SNAKE_CASE SQL column names to PascalCase C# properties.

MapToList to map data from a DbDataReader to a list of objects of type T

private IList<T> MapToList<T>(DbDataReader dr)
{

    var objList = new List<T>();
    var props = typeof(T).GetRuntimeProperties().ToList();
    var colMapping = dr.GetColumnSchema()
        .Where(x => props.Any(y => y.Name.Equals(x.ColumnName.Replace("_", ""), StringComparison.OrdinalIgnoreCase)))
        .GroupBy(g => g.ColumnName)
        .Select(grp => grp.First())
        .ToDictionary(key => key.ColumnName.Replace("_", "").ToLower());

    if (dr.HasRows)
    {
        while (dr.Read())
        {
            T obj = Activator.CreateInstance<T>();
            foreach (var prop in props)
            {
                if (colMapping.ContainsKey(prop.Name.ToLower()))
                {
                    var column = colMapping[prop.Name.ToLower()];
                    if (column?.ColumnOrdinal != null)
                    {
                        var val = dr.GetValue(column.ColumnOrdinal.Value);
                        if (val == null || val == DBNull.Value)
                        {
                            prop.SetValue(obj, null);
                        }
                        else
                        {
                            prop.SetValue(obj, val);
                        }
                    }
                }
            }
            objList.Add(obj);
        }
    }
    return objList;
}

Try this and drop me your feedback.


Similar Articles