Home > Enterprise >  Problem auto mapping models where subfields different objects C#
Problem auto mapping models where subfields different objects C#

Time:07-30

I want via automapper convert CreateUserInputModel to UserModel. CreateUserInputModel has field type of List<int> Options which accept ID's of options. UserModel has field type of List<OptionModel> Options which contain list of OptionModel where is field Id. I tried create mapper ForMember, but when I add it to mapper, an unusual error appears without exception. Mapping error If you have any ideas how 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();

CodePudding user response:

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

  • Related