gpt4 book ai didi

Automapper,将多个属性映射到 1 个没有 ValueResolver

转载 作者:行者123 更新时间:2023-12-02 08:50:13 27 4
gpt4 key购买 nike

我当前的代码正在运行:

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 似乎覆盖了现有的 map 。

我正在尝试将 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 到输出

最佳答案

这样的事情应该工作:

.ForMember(x => x.Address, o => o.MapFrom(
s => new AddressDto {
Latitude = s.ContactInfo.Latitude,
Street = s.Address.Street }));

关于Automapper,将多个属性映射到 1 个没有 ValueResolver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016979/

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