Map a 2nd level nested list property to first level list property with automapper

953 Views Asked by At

I need your help. I have basic experience with automapper and it all works great, but in one way or another i can't map my next change in the source object to my destination object.

Let me explain it a bit:
In IUser, i added a property 'UserDetails' and this class contains a List of Guid property called 'Domains'.

I want to map that second level list property to my UserDto object where the list of guid property is at first level. In the example below, the Userkey mapping works fine, but i keep getting null for 'DomainIds' and don't see what i'm doing wrong. I Hope you can help me

public interface IUser
{
    UserKey Key { get; }
    UserDetails Details { get; set; }
    FirstName { get; }
}

public struct UserKey
{
    private readonly Guid _id;
    public UserKey(Guid id)
    {
        _id = id;
    }
}

public class UserDetails
{
    public List<Guid> Domains { get; set; }
}

public class UserDto
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public List<Guid> DomainIds { get; set; }
}

The mapping setup is the following:

CreateMap<IUser, UserDto>()
            .ForMember(
                dest => dest.Id,
                opt => opt.MapFrom(src => src.Key.Id))
            .ForMember(
                dest => dest.DomainIds,
                opt => opt.MapFrom(src => src.Details.Domains))

In my test i map user (which is an IUser) like this. Fyi, all other properties are mapping fine

_mapper.Map<UserDto>(user);
1

There are 1 best solutions below

0
On

Your mapping appears to work fine for me:

Mapper.Initialize(config =>
{
    config.CreateMap<User, UserDto>()
        .ForMember(
            dest => dest.Id,
            opt => opt.MapFrom(src => src.Key.Id))
        .ForMember(
            dest => dest.DomainIds,
            opt => opt.MapFrom(src => src.Details.Domains));
});

var user = new User
{
    FirstName = "foo",
    Key = new UserKey { Id = Guid.NewGuid() },
    Details = new UserDetails
    {
        Domains = new List<Guid> { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() },
    },
};

var result = Mapper.Map<UserDto>(user);

Using the following types:

public class User
{
    public UserKey Key { get; set; }
    public UserDetails Details { get; set; }
    public string FirstName { get; set; }
}
public class UserKey
{
    public Guid Id {get;set;}
}
public class UserDetails
{
    public List<Guid> Domains { get; set; }
}

public class UserDto
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public List<Guid> DomainIds { get; set; }
}