我不了解自动映射器,但我正在使用ValueInjecter将数据读取器映射到对象,如下所示:
while (dr.Read())
{
var o = new User();
o.InjectFrom<DataReaderInjection>(dr);
return o;
}
和 DataReaderInjection(类似于 Automapper 的 ValueResolver)
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);
}
}
}
您可以使用它将值从 IDataReader 注入任何类型的对象
好的,所以根据你的要求,我想应该是这样的:
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]);
}
}
}
在这里我使用了GetSchemaTable,就像你想要的那样:)
好的,如果您想将一些东西传递给注入,您可以通过多种方式进行,方法如下:
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
这是一个提示(对于带参数的构造函数方式)
public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
{
private IDictionary<string, string> stuff;
public DataReaderInjection(IDictionary<string,string> stuff)
{
this.stuff = stuff;
}
protected override void Inject(
...