1
我當前的代碼工作:Automapper,映射多個屬性到1個W/O ValueResolver
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()< - 從linqpad輸出