Automapper - Map objects with IEnumerable

2019-08-07 10:29发布

问题:

SOLVED: I had a property defined incorrectly!

I'm getting this error... Missing type map configuration or unsupported mapping. Mapping types: HouseDomain -> RoomDomain {namespace}.HouseDomain -> {namespace}.RoomDomain

Destination path: City.Houses.Houses.Houses0[0]

So for example, I have

public class CityDomain
{
    public IEnumerable<HouseDomain> DomainHouses {get;set;}
}
public class HouseDomain
{
    public IEnumerable<RoomDomain> DomainRooms {get;set;}
}    
public class RoomDomain
{
    //whatever
}

and

public class CityDto
{
    public IEnumerable<HouseDto> DtoHouses {get;set;}
}
public class HouseDto
{
    public IEnumerable<RoomDto> DtoRooms {get;set;}
}
public class RoomDto
{
    //whatever
}

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!

回答1:

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));

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);

Produces:

{
   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.



回答2:

You can keep your mappings simplier if you make names of collections the same (e.g. Rooms) for both HouseDomain and HouseDto types.

Mappings:

Mapper.CreateMap<RoomDomain, RoomDto>();
Mapper.CreateMap<HouseDomain, HouseDto>();

Types:

public class HouseDomain
{
    public IEnumerable<RoomDomain> Rooms {get;set;}
}

public class HouseDto
{
    public IEnumerable<RoomDto> Rooms {get;set;}
}

I answered the similar question AutoMapping nested models a while ago.



标签: c# AutoMapper