我目前的代码正在运作:
map.ForMember(x => x.Address, m => m.ResolveUsing(l => {
var engine = new MappingEngine((IConfigurationProvider)cfg);
var adress = engine.Map<AddressDto>(l.ContactInfo);
engine.Map(l.Address, adress);
return adress;
}));
但我认为可能有另一种方式,例如:
map.ForMember(x => x.Address, m => m.MapFrom(x => x.ContactInfo));
map.ForMember(x => x.Address, m => m.MapFrom(x => x.Address));
但是最后的ForMember似乎覆盖了现有的地图。
我正在尝试将Address和ContactInfo属性组合到ListingDto.Address上的单个对象中。
void Main()
{
var map = Mapper.CreateMap<Listing, ListingDto>();
var cfg = Mapper.Configuration;
map.ForMember(x => x.Address, m => m.ResolveUsing(l => {
var engine = new MappingEngine((IConfigurationProvider)cfg);
var adress = engine.Map<AddressDto>(l.ContactInfo);
engine.Map(l.Address, adress);
return adress;
}));
Mapper.CreateMap<Address, AddressDto>()
.ForMember(x => x.Latitude, x => x.Ignore());
Mapper.CreateMap<ContactInfo, AddressDto>()
.ForMember(x => x.Street, x=> x.Ignore());
Mapper.Map<ListingDto>(new Listing{
Name="Foo",
Address = new Address{Street = "Street"},
ContactInfo = new ContactInfo{ Latitude = "latitude"}}).Dump();
}
// Define other methods and classes here
public class Listing{
public string Name { get; set; }
public Address Address { get; set; }
public ContactInfo ContactInfo {get;set;}
}
public class ContactInfo{
public string Latitude {get;set;}
}
public class Address{
public string Street {get;set;}
}
public class AddressDto{
public string Latitude {get;set;}
public string Street {get;set;}
}
public class ListingDto{
public string Name { get; set; }
public AddressDto Address {get;set;}
}
.Dump()&lt; - 从linqpad到输出
答案 0 :(得分:6)
这样的事情应该有效:
.ForMember(x => x.Address, o => o.MapFrom(
s => new AddressDto {
Latitude = s.ContactInfo.Latitude,
Street = s.Address.Street }));