Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

asp.net mvc - Automapper mapping list becomes 0

I'm mapping a list to another list with Automapper, but it seems that my items are not copied.

Here is my code:

var roles = userRepo.GetRoles(null).ToList();
Mapper.CreateMap < List<Domain.Role>, List<Role>>();
var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles); //the count is 0, list empty :(
Mapper.AssertConfigurationIsValid();
  1. No exceptions were thrown.
  2. All properties has the same names.

Domain.Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<User> Users { get; set; }
}

Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Don't create maps between lists and array, only between the types:

Mapper.CreateMap<Domain.Role, Role>();

and then:

var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles);

AutoMapper handles lists and arrays automatically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...