Search code examples
c#.netautomapper

AutoMapper - Problem in mapping models which the subfields are different objects


Via AutoMapper, I want to convert CreateUserInputModel to UserModel.

CreateUserInputModel has a property: List<int> Options which accepts IDs of options. UserModel has a property: List<OptionModel> Options which contains the list of OptionModel which has the field Id. I tried to create a mapper ForMember, but when I add it to the mapper, an unusual error appears without exception.

Mapping error

If you have any ideas on how to resolve this mapping, I will be very grateful. Thank you!

CreateUserInputModel

public class CreateUserInputModel
{
    public string Email { get; set; } = string.Empty;
    public string Firstname { get; set; } = string.Empty;
    public string Lastname { get; set; } = string.Empty;
    public DateTime EmploymentDate { get; set; }
    public int WorkTypeId { get; set; }
    public List<int>? Options { get; set; } = new List<int>();
}

UserModel

public class UserModel
{
    public int Id { get; set; }
    public string Email { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    public string Firstname { get; set; } = string.Empty;
    public string Lastname { get; set; } = string.Empty;
    public int VacationDays { get; set; }
    public DateTime EmploymentDate { get; set; }
    public WorkTypeModel WorkType { get; set; } = new WorkTypeModel();
    public List<OptionModel>? Options { get; set; } = new List<OptionModel>();
}

User mapper

CreateMap<UserModel, CreateUserInputModel>()
    .ForMember(dest => dest.WorkTypeId, opt => opt.MapFrom(src => src.WorkType.Id))
    .ForMember(dest => dest.Options, opt => opt.MapFrom(src => src.Options.Select(option => option.Id).ToList()))
    .ReverseMap();

Solution

  • Think that you miss out on the mapping configuration for mapping from int to OptionModel and vice versa.

    CreateMap<int, OptionModel>()
        .AfterMap((src, dest) => 
        {
            dest.Id = src;
        });
    
    CreateMap<OptionModel, int>()
        .ConstructUsing(src => src.Id);
    

    Sample .NET Fiddle