I don't know about automapper but I'm mapping datareader to objects using the ValueInjecter like this:
while (dr.Read())
{
var o = new User();
o.InjectFrom<DataReaderInjection>(dr);
return o;
}
and the DataReaderInjection (something like ValueResolver for Automapper)
public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
{
protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
{
for (var i = 0; i < source.FieldCount; i++)
{
var activeTarget = targetProps.GetByName(source.GetName(i), true);
if (activeTarget == null) continue;
var value = source.GetValue(i);
if (value == DBNull.Value) continue;
activeTarget.SetValue(target, value);
}
}
}
you can use this to inject values from an IDataReader to any type of object
ok, so according to your requirements, I guess it should be like this:
public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
{
protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
{
var columns = source.GetSchemaTable().Columns;
for (var i = 0; i < columns.Count; i++)
{
var c = columns[i];
var targetPropName = c.ColumnName; //default is the same as columnName
if (c.ColumnName == "Foo") targetPropName = "TheTargetPropForFoo";
if (c.ColumnName == "Bar") targetPropName = "TheTargetPropForBar";
//you could also create a dictionary and use it here
var targetProp = targetProps.GetByName(targetPropName);
//go to next column if there is no such property in the target object
if (targetProp == null) continue;
targetProp.SetValue(target, columns[c.ColumnName]);
}
}
}
here I used GetSchemaTable, just like you wanted :)
ok, if you want to pass some stuff to the injection, you can do it in many ways, here's how:
o.InjectFrom(new DataReaderInjection(stuff), dr);
//you need a constructor with parameters for the DataReaderInjection in this case
var ri = new DataReaderInjection();
ri.Stuff = stuff;
o.InjectFrom(ri, dr);
//you need to add a property in this case
here's a hint (for the constructor with parameters way)
public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
{
private IDictionary<string, string> stuff;
public DataReaderInjection(IDictionary<string,string> stuff)
{
this.stuff = stuff;
}
protected override void Inject(
...