自动映射器-使用IEnumerable< anotherType>映射对象 [英] Automapper - Map objects with IEnumerable<anotherType>
问题描述
已解决:我的属性定义不正确!
SOLVED: I had a property defined incorrectly!
我收到此错误... 缺少类型映射配置或不支持的映射. 映射类型: HouseDomain-> RoomDomain {namespace} .HouseDomain-> {namespace} .RoomDomain
I'm getting this error... Missing type map configuration or unsupported mapping. Mapping types: HouseDomain -> RoomDomain {namespace}.HouseDomain -> {namespace}.RoomDomain
目标路径: City.Houses.Houses.Houses0 [0]
Destination path: City.Houses.Houses.Houses0[0]
例如,我有
public class CityDomain
{
public IEnumerable<HouseDomain> DomainHouses {get;set;}
}
public class HouseDomain
{
public IEnumerable<RoomDomain> DomainRooms {get;set;}
}
public class RoomDomain
{
//whatever
}
和
public class CityDto
{
public IEnumerable<HouseDto> DtoHouses {get;set;}
}
public class HouseDto
{
public IEnumerable<RoomDto> DtoRooms {get;set;}
}
public class RoomDto
{
//whatever
}
所以我想将CityDomain映射到CityDto.我有...
So I want to map CityDomain to CityDto. I have...
Mapper.CreateMap<CityDomain , CityDto>();
是否存在像这样的两个层次的问题?有什么帮助吗?谢谢!
Is there an issue going 2 levels deep like this? Any help? Thanks!
推荐答案
这就是您需要的所有映射(如果已创建了适用于对象类型的映射,则Automapper足够聪明来映射对象列表):
This is all mappings you need (Automapper is smart enough to map lists of objects if mapping for appropriate object types was created):
Mapper.CreateMap<RoomDomain, RoomDto>();
Mapper.CreateMap<HouseDomain, HouseDto>()
.ForMember(d => d.DtoRooms, m => m.MapFrom(s => s.DomainRooms));
只需删除成员DtoRooms的第二个映射.例如.如果房子有ID,房间有名字,那么对于示例域来说,房子映射就可以了:
Just remove your second mapping for member DtoRooms. E.g. if house has id and room has name, then for sample domain house mapping works just fine:
HouseDomain domainHouse = new HouseDomain
{
Id = 42,
DomainRooms = new List<RoomDomain>
{
new RoomDomain { Name = "foo" },
new RoomDomain { Name = "bar" }
}
};
var dtoHouse = Mapper.Map<HouseDto>(domainHouse);
产生:
{
Id: 42,
DtoRooms: [ { Name: "foo" }, { Name: "bar" } ]
}
最后一点-确保在进行映射之前先创建地图.通常,所有地图都是在应用程序启动时创建的.
Last note - make sure you create maps before you are doing mapping. Usually all maps are created on application startup.
这篇关于自动映射器-使用IEnumerable< anotherType>映射对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!