1

Class with IList<Object> member:

public class RegisterGroupEmployeeRequest : GroupEmployeeBase
{
    public IList<EmployeeBase> Employee { get; set; }
}

Class with IEnumerable<OtherObject> member:

public class RegisterGroupEmployeeCommand
{
    public RegisterGroupEmployeeCommand(Guid groupId, IList<EmployeeCommand> employee)
    {
        Employee = employee;
    }

    public IEnumerable<EmployeeCommand> Employee { get; protected set; }
}

Mapper:

CreateMap<RegisterGroupEmployeeRequest, RegisterGroupEmployeeCommand>()
    .ConstructUsing(src => new RegisterGroupEmployeeCommand(src.GroupId, src.Employee));

How can I convert data of IList<Object> to IEnumerable<OtherObject> with AutoMapper?
Or is there any another solution for converting this kind issue?

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Do you have the `CreateMap` in your configuration? Do you get any errors? – kasptom Aug 26 '20 at 11:44
  • I already write that above this code. ``` CreateMap(); CreateMap() .ConstructUsing(src => new RegisterGroupEmployeeCommand(src.GroupId, src.Employee)); ///Error ``` *Error : ``` cannot convert from 'System.Collections.Generic.IList' to 'System.Collections.Generic.IList' [Xtpo.Security.WebApi] ``` – Ravi Algifari Aug 26 '20 at 11:52
  • What version of AutoMapper do you use? What is the reason of `Guid groupId` in the constructor of the `RegisterGroupEmployeeCommand` if you do not assign it anywhere? – kasptom Aug 26 '20 at 17:06
  • Does this answer your question? [Automapper copy List to List](https://stackoverflow.com/questions/8899444/automapper-copy-list-to-list) – EJoshuaS - Stand with Ukraine Aug 28 '20 at 22:28

1 Answers1

0

tl;dr

Remove the .ConstructUsing() and leave the entry like below:

CreateMap<RegisterGroupEmployeeRequest, RegisterGroupEmployeeCommand>();

  1. In this line:
.ConstructUsing(src => new RegisterGroupEmployeeCommand(src.GroupId, src.Employee));

Your Employee is of IList<EmployeeCommand> type but you are trying to pass IList<EmployeeBase> instead.

  1. Since you already have the entry like:
CreateMap<EmployeeBase, EmployeeCommand>();

AutoMapper will handle the conversion from IList<EmployeeBase> to IList<EmployeeCommand> as well.

  1. Passing Group goupId seems to be unnecessary as you don't use it in the constructor body.
public RegisterGroupEmployeeCommand(Guid groupId, IList<EmployeeCommand> employee)
{
    Employee = employee;
}
  1. Looking at point 2. and 3. you don't need the .ConstructUsing(...) line.
kasptom
  • 2,363
  • 2
  • 16
  • 20