HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

DataTable to given type T simple mapper

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpledatatablemappertypegiven

Problem

I threw this together and would love any suggestions on how to improve on this simple DataTable to given Type T mapper. Anything from coding conventions to speed optimizations or "you're doing something stupid".

```
public class test {

static ISXLog log = new XLog();

public void runTest() {
var data = RetrieveDataSet(/parameters not important/);
AddressType[] addr = mapObjects(data.Tables[0]);
}

// overload for optional function parameter
public static T[] mapObjects(DataTable dt ) where T : new(){
return mapObjects(dt, (p => p.IsCollection()));
}

// mapObjects from DataTable to Type T
public static T[] mapObjects(DataTable dt, FuncpropRestriction) where T : new() {
T[] newobjs;
var Rows = dt.Rows;
newobjs = new T[Rows.Count];
var MField = typeof(DataRowExtensions)
.GetMethod(@"Field", new[] { typeof(DataRow), typeof(string) });

for (int i = 0; i < Rows.Count; i++) {
DataRow dbobj = Rows[i];
var obj = newobjs[i] = new T();
var objProps = obj.GetType().GetProperties();

foreach (var prop in objProps) {
try {
if (!dbobj.Table.Columns.Contains(prop.Name) || propRestriction(prop)) {
log.Debug("Nothing to set for property: {0}", prop.Name);
}else{
MField = MField.GetGenericMethodDefinition()
.MakeGenericMethod(prop.PropertyType);

var objval = MField.Invoke(null, new object[] { dbobj, prop.Name });
prop.SetValue(obj, objval, null);
log.Debug("Set property '{0}' to value '{1}'", prop.Name, objval);

}
}
catch (Exception e) {
log.DebugException("Error occured while trying to set prop: " + prop.Name, e);
}
}
}
return newobjs;
}

public static class PropertyInfoExtensions
{
public static bool IsCollection(this PropertyInfo property) {
return (!typeof(String).Equals(property.PropertyType) &&
typeof(I

Solution


  • You can minimize you code taking out the filtering out side of loop.



  • Avoid catching exception inside a loop if it needed ,(it seems like it cannot be avoided here)



  • No need to invoke datarow extension method to get value , you can get it directly.



  • Naming of variable is really bad.



This is first round of re factoring.

public static T[] MapObjects(DataTable dataTable, Func 
 propRestriction) where T : new()
{
var mappedObjectProperties = typeof(T).GetProperties()
                                       .Where(elem => !propRestriction(elem)).ToList();
var mappedObjectCollection = new List();
foreach (var dataRow in dataTable.AsEnumerable())
{
    var mappedObject = new T();
    foreach (var mappedObjectProperty in mappedObjectProperties)
    {
        if (dataTable.Columns.Contains(mappedObjectProperty.Name))
        {
            var value = dataRow[mappedObjectProperty.Name];
            mappedObjectProperty.SetValue(mappedObject, value, null);
        }
        else
        {
            log.Debug("Nothing to set for property: {0}", prop.Name);
        }
    }
    mappedObjectCollection.Add(mappedObject);
  }
  return mappedObjectCollection.ToArray();
}

Code Snippets

public static T[] MapObjects<T>(DataTable dataTable, Func<PropertyInfo, bool> 
 propRestriction) where T : new()
{
var mappedObjectProperties = typeof(T).GetProperties()
                                       .Where(elem => !propRestriction(elem)).ToList();
var mappedObjectCollection = new List<T>();
foreach (var dataRow in dataTable.AsEnumerable())
{
    var mappedObject = new T();
    foreach (var mappedObjectProperty in mappedObjectProperties)
    {
        if (dataTable.Columns.Contains(mappedObjectProperty.Name))
        {
            var value = dataRow[mappedObjectProperty.Name];
            mappedObjectProperty.SetValue(mappedObject, value, null);
        }
        else
        {
            log.Debug("Nothing to set for property: {0}", prop.Name);
        }
    }
    mappedObjectCollection.Add(mappedObject);
  }
  return mappedObjectCollection.ToArray();
}

Context

StackExchange Code Review Q#59452, answer score: 2

Revisions (0)

No revisions yet.