1
votes

I'm new to Automapper, and trying to map a Entity Framework database object to a DTO.

My database object, OfficeLookup, contains Code and Description (among other properties I'm not concerned with). My OfficeDto contains Id and Name properties.

The mapping:

private MapperConfiguration OfficeMapperConfiguration =>
    new MapperConfiguration(
        cfg =>
            {
                cfg.CreateMap<OfficeLookup, OfficeDto>()
                    .ForMember(dest => dest.Id, act => act.MapFrom(src => src.Code))
                    .ForMember(dest => dest.Name, act => act.MapFrom(src => src.Description));
            });

And my code:

public IEnumerable<OfficeDto> GetOfficeDtos() => OfficeLookup.ProjectTo<OfficeDto>(OfficeMapperConfiguration); // returns an Ienumerable of empty OfficeDTOs

The strange thing is that I have another, more complex mapping for a different table which works fine. I don't understand why this map doesn't.

The expression generated by my mapping is

ObjectQuery<OfficeLookup>.MergeAs(MergeOption.AppendOnly).Select(dtoOfficeLookup => new OfficeDto())

which doesn't look right. The other mapping generates an expression which set the various properties correctly (with the exception of the Office value. I assume that once I can get this standalone mapping, I will be able to fix the nested mapping).

1
@IvanStoev you are indeed right, my bad, too early and no coffee yet :-) Sorry about that - Jcl

1 Answers

2
votes

The problem should be in corresponding OfficeDto properties, and more specifically, the lack of property setter, in which case AutoMapper simply skips them from projection even though they have been mapped explicitly.

e.g. the issue is reproduced with the following class:

class OfficeDto
{
    public int Id { get; }
    public string Name { get; }
}

And adding property setters (even private) fixes it:

class OfficeDto
{
    public int Id { get; private set; }
    public string Name { get; set; }
}