Created
May 8, 2015 17:56
-
-
Save Whiteknight/4338aa0272c6a65740f6 to your computer and use it in GitHub Desktop.
Map DataRow to nested object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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