Skip to content

Instantly share code, notes, and snippets.

@Whiteknight
Created May 8, 2015 17:56
Show Gist options
  • Save Whiteknight/4338aa0272c6a65740f6 to your computer and use it in GitHub Desktop.
Save Whiteknight/4338aa0272c6a65740f6 to your computer and use it in GitHub Desktop.
Map DataRow to nested object
private CreateItem<T>(DataRow row)
where T : new()
{
T item = new T();
foreach (PropertyInfo property in typeof(T).GetProperties())
{
MapFromDataRow(row, "", property, item);
}
return item;
}
private void MapFromDataRow(DataRow row, string prefix, PropertyInfo property, object obj)
{
string columnName = string.IsNullOrEmpty(prefix) ? prefix : prefix + "_" + property.Name;
if (property.PropertyType.IsValueType)
{
object value = row[columnName];
property.SetValue(object, value);
return;
}
object childObj = Activator.CreateInstance(property.PropertyType);
property.SetValue(object, childObj);
foreach (PropertyInfo childProperty in property.PropertyType.GetProperties())
{
MapFromDataRow(row, columnName, childProperty, childObj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment