How to convert from List<> to Ilist<> using Automapper?

Asked

Viewed 126 times

0

I need to convert a List to Ilist with automapper knowing that both are in different classes and one of them has a constructor. Is that possible? I’m using the Automapper 6.2.2.

public class Pessoa
{
    public int Id { get; set; }
    public int Nome { get; set; }   
}

public class MinhasPessoas
{
    public List<Pessoa> Pessoas { get; set; }
}

public abstract class RegisterNewPessoas
{
    public IList<Pessoa> Pessoas { get; set; }

    RegisterNewPessoas(IList<Pessoa> pessoas)
    {
        Pessoas = pessoas;
    }
}

Mapping:

CreateMap<MinhasPessoas, RegisterNewPessoa>()
    .ConstructUsing(ps => new RegisterNewPessoa(//Converter as listas aqui));

1 answer

2

You don’t have to do any conversion. List<> implements IList<>, then any instance of List<> can be assigned to a variable IList<>.

I don’t even know if it’s necessary to use the method ConstructUsing in that case. If it is, just do the assignment.

ConstructUsing(ps => new RegisterNewPessoa { Pessoas = ps.Pessoas }

See a functional example in . NET Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.