具有动态目标属性的AutoMapper

我们正在尝试创建一个允许用户在类和数据库值之间映射属性的工具。

我想使用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中是一个可能的壮举吗? 谢谢

链接地址: http://www.djcxy.com/p/37363.html

上一篇: AutoMapper with dynamic destination property

下一篇: Automapper: Target TypeConverter to specific objects