简体   繁体   中英

Automapper how to map list of one object to list of another object

I am using the following mapping to map my data object to viewmodel object

Source:

public class User
{
    public string Id { get; set; }
    public IList<Address> Addresses {get;set;}
}

public class Address
{
    public string Id {get;set;}
    public string Name {get;set;}
}

Destination:

public class UserViewModel
{
    public string Id {get;set;}
    public IEnumerable<VMAddress> VMAddress {get;set;}
}

public class VMAddress
{
    public string Name{get;set;}
}

Mapping:

Mapper.CreateMap<IList<Address>, IList<VMAddress>>();
Mapper.CreateMap<User, UserViewModel>()
            .ForMember(d=>d.VMAddress, e=>e.MapFrom(s=> new List<Address>
            {
                new VMAddress
                {
                    Name = s.Id
                }
            }))

My mapping is not working as expected. How do i map the list of id property of the source to list of name property in the destination?

Getting the following error:

Missing type map configuration or unsupported mapping.

Mapping types:
List`1 -> User
System.Collections.Generic.List`1[[User, ...., Version=1.1.0.0, Culture=neutral, PublicKeyToken=null]] -> UserViewModel

Destination path:
UserViewModel

Source value:
System.Collections.Generic.List`1[User]

Thanks

This mapping works fine -

Mapper.CreateMap<User, UserViewModel>()
            .ForMember(a => a.Id, b => b.ResolveUsing(c => c.Id))
            .ForMember(a => a.VMAddress, b => b.ResolveUsing(c => c.Addresses));

Mapper.CreateMap<Address, VMAddress>()
            .ForMember(a => a.Name, b => b.ResolveUsing(c => c.Name));
var map = Mapper.Map<UserViewModel>(new User
        {
            Id = "ID",
            Addresses = new List<Address>
            {
                new Address{ Name = "name1"} ,
                new Address{ Name = "name2"}
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM