gpt4 book ai didi

automapper - 在 AutoMapper 中将复杂类型映射到平面类型

转载 作者:行者123 更新时间:2023-12-04 01:14:11 32 4
gpt4 key购买 nike

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

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

我已经配置了 AutoMapperTradingDesk :

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我不得不重新配置 AutoMapperTradingDesk像这样:

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需要映射时,应该使用已经配置好的源和目标类型映射 TradingDeskRow映射时 BusinessUnit .通过这种方式,我可以从最小类型到最大类型构建配置,同时展平复杂对象,而无需为展平类型中的每个单独成员定义映射。

最佳答案

实际语法可能会有所不同,因为我以静态方式使用 AutoMapper,但原理保持不变:

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

关于automapper - 在 AutoMapper 中将复杂类型映射到平面类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131114/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com