I have a complex object like:
public class BusinessUnit
{
public TradingDesk TradingDesk { get; }
public string Division { get; }
public BusinessUnit(string division, TradingDesk tradingDesk)
{
Division = division;
TradingDesk = tradingDesk;
}
}
I want to map this to the flat type:
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; }
}
I have already configured AutoMapper
for TradingDesk
:
CreateMap<TradingDesk, Row>().ForMember(vm => vm.TradingDeskName, op => op.MapFrom(src => src.Name));
so the following test is passing:
[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);
}
But when I try to map BusinessUnit
to Row
I am having to reconfigure AutoMapper
for TradingDesk
as such:
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));
I expect that AutoMapper
should use the already configured source & destination type mapping when it needs to map TradingDesk
to Row
while mapping BusinessUnit
. This way I can build the configuration from the smallest to the largest type while flattening out a complex object without having to define mapping for each individual member in the flattened type.
How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.
Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .
The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping. As of now, the mapping we discussed are one directional means if we have two types let's say Type A and Type B, then we Map Type A with Type B.
Actual syntax might differ because I'm using AutoMapper in a static manner, but the principle remains the same:
Mapper.CreateMap<BusinessUnit, Row>()
.ConvertUsing(source => Mapper.Map<TradingDesk, Row>(source.TradingDesk));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With