AutoMapper with dynamic destination property

We are attempting to create a tool that allows users to map properties between classes and database values.

I'd like to use AutoMapper to map from the DataRow to a class, so long as we manually create the mapping for each property. For example

 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]));

This will SUCCESSFULLY map from a DataRow (r) on the field selected by fields.FirstOrDefault.

To make it more generic, I'd like to loop through each property and add the property based on the property name.

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]));
}

However, I can't seem to set the DESTINATION dynamically, and have to use

p => p.Property, 

I can't do

p => p.GetType().GetProperty(propName) 

Is this a possible feat in AutoMapper? Thanks

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

上一篇: 使用AutoMapper从列表向下映射到对象

下一篇: 具有动态目标属性的AutoMapper