自动映像如何将一个对象的列表映射到另一个对象的列表

时间:2016-06-21 10:19:20

标签: c# automapper

我使用以下映射将我的数据对象映射到viewmodel对象

来源:

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

目的地:

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

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

映射:

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

我的映射无法按预期工作。如何将源的id属性列表映射到目标中的name属性列表?

收到以下错误:

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]

由于

1 个答案:

答案 0 :(得分:2)

此映射工作正常 -

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