我们正在尝试创建一个工具,允许用户在类和数据库值之间映射属性。
我想使用AutoMapper从DataRow
映射到类,只要我们手动为每个属性创建映射。例如
cfg.CreateMap<DataRow, SupplierInventory>()
.ForMember(m => m.Id,
s => s.MapFrom(r =>
r[
fields.FirstOrDefault(c =>
c.DestinationTable == nameof(SupplierInventory) &&
c.DestinationField == nameof(SupplierInventory.Id)).SourceField]))
.ForMember(m => m.Description,
s => s.MapFrom(r =>
r[
fields.FirstOrDefault(c =>
c.DestinationTable == nameof(SupplierInventory) &&
c.DestinationField == nameof(SupplierInventory.Description)).SourceField]))
.ForMember(m => m.Size,
s => s.MapFrom(r =>
r[
fields.FirstOrDefault(c =>
c.DestinationTable == nameof(SupplierInventory) &&
c.DestinationField == nameof(SupplierInventory.Size)).SourceField]));
这将成功地通过fields.FirstOrDefault选择的字段上的DataRow(r)映射。
为了使其更通用,我想循环遍历每个属性并根据属性名称添加属性。
IMappingExpression<DataRow, SupplierInventory> map = new MappingExpression<DataRow, SupplierInventory>(MemberList.None);
var props = typeof(SupplierInventory).GetProperties();
foreach (var prop in props)
{
map.ForMember(p => p.Id, s => s.MapFrom(r =>
r[
fields.FirstOrDefault(c =>
c.DestinationTable == nameof(SupplierInventory) &&
c.DestinationField == prop.Name).SourceField]));
}
但是,我似乎无法动态设置 DESTINATION ,并且必须使用
p => p.Property,
我无法做到
p => p.GetType().GetProperty(propName)
这是AutoMapper中可能的壮举吗?感谢