When mapping class to viewModel, some data is lost

Asked

Viewed 211 times

3

I have an appointment that returns a client and his phone, but when mapping the class to the viewModel, I lose phone data:

consultation:

public Cliente ObterClientePorId(Guid ClienteId)
{
      var consulta =
            Contexto.Cliente.Join(Contexto.Telefone,
                                  p => p.ClienteId, 
                                  pt => pt.ClienteId,
                                 (p, pt) => new {p, pt}).FirstOrDefault();

  if (consulta != null)
  {
      var cliente = consulta.p;
      cliente.telefone = consulta.pt;

      return cliente;
 }

But when mapping the client class to the viewModel cliente, it loses the data that was in telefone.

Mapping:

    public ClienteViewModel ObterClientePorId(Guid ClienteId)
    {
        //aqui tem os dados de telefone
        var consulta = _cliente.ObterClientePorId(ClienteId);
        //aqui o telefone fica null
        var cliente = Mapper.Map<Cliente, ClienteViewModel>(consulta);

        return cliente;
    }

ClienteViewModel:

public class ClienteViewModel
{
    public ClienteViewModel()
    {
        ClienteId = Guid.NewGuid();
    }

    // campos...

    public List<TelefoneViewModel> TelefoneViewModel { get; set; }

    //mais campos...
}
  • Already tried not to use Automapper?

  • I didn’t try, then I would do the hand mapping?

  • 1

    Yes, using implicit operators, for example.

1 answer

4


Have you tried mapping the Phone class to "Phoneviewmodel"? I say this because your class Clienteviewmodel has a List< Phoneviewmodel> and not List< Phone>.

Maybe this will work:

var telefones = Mapper.Map<List<Telefone>, List<TelefoneViewModel>>(consulta.telefone);
var cliente = Mapper.Map<Cliente, ClienteViewModel>(consulta);
cliente.TelefoneViewModel = telefones;

If it doesn’t work, share your Customer and Phone classes, please.

Hugs.

  • this way worked, thanks! I had tried to do something similar, I just had not done that cast to list.

  • @austin How would you look if the query returned a list of customers, how would you map these phones?

  • @Alexandrepreviatti did not understand the question right. If you return a list of customers, do not need Cast, right?

  • @Austunhappy as it is returned only one customer, I can recover the phones with "phone.query" if it were a customer list would not be possible... The question is, if instead of: var client = Mapper.Map<Client, Clienteviewmodel>(query); were var client = Mapper.Map<List<Client>, List<Clienteviewmodel>>(query); assuming the query was a customer list, how would this mapping of phones?

  • 1

    @Alexandrepreviatti I get it. It allows you to put the actions of mapping inside a foreach, IE, you take a list of customers, do the foreach in the list and do the same answer ai process.

Browser other questions tagged

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