Simple Automapper Example

1- Change the GroupDto to be like this:

[DataContract]
public class GroupDto
{
    [DataMember]
    public int id { get; set; }
    [DataMember]
    public string name{ get; set; }
    [DataMember]
    public List<UserDTO> Users { get; set; }      
}

2- Create your mappings :

Mapper.CreateMap<User, UserDto>();
Mapper.CreateMap<UserDto, User>(); // Only if you convert back from dto to entity

Mapper.CreateMap<Group, GroupDto>();
Mapper.CreateMap<GroupDto, Group>(); // Only if you convert back from dto to entity

3- that’s all, because auto mapper will automatically map the List<User> to List<UserDto> (since they have same name, and there is already a mapping from user to UserDto)

4- When you want to map you call :

Mapper.Map<GroupDto>(groupEntity);

Hope that helps.

Leave a Comment