Map a property to Enum

Asked

Viewed 46 times

0

I’m starting automapper studies so I don’t even know if I’m using the correct terms to ask the question, but here’s the thing. I have the class Patient that, among other properties, has an Enum called State, which as you may assume, are the states of Brazil. In the database, the patient table stores in the status column an int with the Enum code representing the status.

  public class Paciente
  {
     public Estado Estado { get; set; }
  }

Using the automapper, I created the method

private readonly IBaseService<Paciente> _service;
    private readonly IMapper _mapper;

  public async Task<IEnumerable<PacienteViewModel>> GetAsync()
    {
        var pacientes = await _service.GetAsync();
        var result = pacientes.Select(t => _mapper.Map<Paciente, PacienteViewModel>(t)).ToList();
        return result;
    }

But calling this method gives the following error:

Unable to cast Object of type 'System.String' to type 'System.Int32'.

Which I suspect is because of this Enum, but I’m not sure, nor idea what to do to test.

  • 1

    Property Status of your Patienteviewmodel is a string?

  • How is your Enum defined and what you are posting to the controller, enumerator or displayname?

  • @Marcosjunior is the same

  • @Leandroangelo o Enum has dysplasia, but at this point I’m not even using it. That’s why I suspect the automapper isn’t converting his code to map

  • The error message says that you are posting a string in a property that expects an int

1 answer

0

Patient and Patientviewmodel must have the same types of data, or else you must inform the conversion manually.

 .ForMember(dest => dest.Estado, opt => opt.MapFrom(src => (EstadoEnum)src.Estado))

Browser other questions tagged

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