在AutoMapper中将复杂类型映射为平面类型



我有一个复杂的对象,如:

public class BusinessUnit
{
        public TradingDesk TradingDesk { get; }
        public string Division { get; }
        public BusinessUnit(string division, TradingDesk tradingDesk)
        {
            Division = division;
            TradingDesk = tradingDesk;
        }
}

我想把它映射到平面类型:

public class Row
{
   //TradingDesk properties
   public string TraderFirstName { get; set; }
   public string TraderLastName { get; set; }
   public string TradingDeskName { get; set; }
   public string Division { get; set; }
}

我已经为TradingDesk配置了AutoMapper:

CreateMap<TradingDesk, Row>().ForMember(vm => vm.TradingDeskName, op => op.MapFrom(src => src.Name));

所以下面的测试通过了:

[Test]
public void Should_Map_TradingDesk_To_Row()
{
    var tradingDesk = Fixture.Create<TradingDesk>();
    var mapped = AutoMapper.Map<Row>(tradingDesk);
    mapped.TradingDeskName.Should()
            .Be(tradingDesk.Name);
    mapped.TraderFirstName.Should()
            .Be(tradingDesk.Trader.FirstName);
    mapped.TraderLastName.Should()
            .Be(tradingDesk.Trader.LastName);
}

但是当我试图将BusinessUnit映射到Row时,我不得不为TradingDesk重新配置AutoMapper:

CreateMap<BusinessUnit, Row>()
   .ForMember(vm => vm.TradingDeskName, op => op.MapFrom(src => src.TradingDesk.Name))
   .ForMember(vm => vm.TraderFirstName, op => op.MapFrom(src => src.TradingDesk.Trader.FirstName))
   .ForMember(vm => vm.TraderLastName, op => op.MapFrom(src => src.TradingDesk.Trader.LastName));

我希望AutoMapper应该使用已经配置好的源&在映射BusinessUnit时,需要将TradingDesk映射到Row。通过这种方式,我可以构建从最小到最大类型的配置,同时将复杂对象扁平化,而不必为扁平化类型中的每个单独成员定义映射。

实际语法可能不同,因为我以静态方式使用AutoMapper,但原则是相同的:

Mapper.CreateMap<BusinessUnit, Row>()
      .ConvertUsing(source => Mapper.Map<TradingDesk, Row>(source.TradingDesk));

首先我认为你的交易台地图应该是

CreateMap<TradingDesk, Row>();

如果我没记错的话,因为你的目标成员与源成员名匹配。',则不需要显式指定。

如果您将Row类更改为

public class Row
{
   //TradingDesk properties
   public string TradingDeskTraderFirstName { get; set; }
   public string TradingDeskTraderLastName { get; set; }
   public string TradingDeskName { get; set; }
   public string Division { get; set; }
}

你的地图将是

CreateMap<BusinessUnit, Row>(); 

如果您永远不打算映射到TradingDesk,那么删除该映射。

如果这是在某些配置文件中定义的,你也可以说

RecognizePrefixes("TradingDesk"); 

,然后不需要更改Row类

如果您不想创建特殊的转换器或属性解析器,您可以在主对象的映射之后执行第二次映射,例如:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<TradingDesk, Row>()
        .ForMember(vm => vm.TradingDeskName, op => op.MapFrom(src => src.Name));
    cfg.CreateMap<BusinessUnit, Row>()
        .AfterMap((businessUnit, row) => { Mapper.Map(businessUnit.TradingDesk, row); });
});
var source = new BusinessUnit("division", new TradingDesk { TraderFirstName = "FirstName", TraderLastName = "LastName", Name = "DeskName" });
var dest = Mapper.Map<Row>(source);

在本例中,对象已被映射,而没有创建新实例。

相关内容

  • 没有找到相关文章

最新更新