Bob Tway
Bob Tway

Reputation: 9613

AutoMapper failing to convert simple DTO

Currently working through some legacy code, changing from DTOs built manually to using Automapper. All been going fine until I came to this relatively simple class:

public class JobRoleCompanyTypeDto
{
    public int Id { get; set; }
    public string Description { get; set; }
    public string ResourceDescription { get; set; }
}

We use localisation and some strings require translation, so I added this to the automapper config, as I've done for other such properties:

cfg.CreateMap<JobRoleCompanyType, JobRoleCompanyTypeDto>()
   .ForMember(dto => dto.Description, opt => opt.MapFrom(jrc => jrc.Description.Translate()));  

But when I actually come to test it:

JobRoleCompanyType testJrc = _context.JobRoleCompanyTypes.First();
var mappedJrc = Mapper.Map<JobRoleCompanyTypeDto, JobRoleCompanyType>(testJrc);

It refuses to compile, giving the error

cannot convert from 'MyNamespace.Entity.Model.JobRoleCompanyType' to 'MyNamespace.DAL.Model.JobRoleCompanyTypeDto'

I've mapped plenty of other types in this way, so I'm baffled as to why this one doesn't work. No doubt I've missed something stupid and simple, but I can't see what it is?

Upvotes: 2

Views: 108

Answers (1)

YuvShap
YuvShap

Reputation: 3835

You have confused the order between the source type and the destination type, try this:

var mappedJrc = Mapper.Map<JobRoleCompanyType,JobRoleCompanyTypeDto>(testJrc);

You can also use another overload that accepts object parameter as input and ommit the source type at all:

var mappedJrc = Mapper.Map<JobRoleCompanyTypeDto>(testJrc);

Upvotes: 4

Related Questions