User48591
User48591

Reputation: 301

Automapper ForMember MapFrom doesn't seem to be working

public class Source
{
    public SourceId Identification { get; }
}

public class SourceId 
{
    public string Id { get; }
}

public class Destination
{
    public string Identification { get; set; }
}

public class SourceProfile : Profile
{
    public SourceProfile()
    {
        CreateMap<Source, Destination>().ForMember(dest => dest.Identification, opt => opt.MapFrom(src => src.Identification.Id));
    }
}
---------------------------------------------------------------------

// On startup of the application

var config = new MapperConfiguration(cfg => cfg.AddProfile<SourceProfile>());
var mapper = config.CreateMapper();

---------------------------------------------------------------------

// The mapper is injected into the class where the following code is used
var dest = mapper.Map<Source, Destination>(source);
var destId = dest.Identification;

The value of destId is "Source.SourceId". Basically the ToString() representation of the SourceId object. The mapper is not taking into account the individual member mapping for some reason.

Upvotes: 1

Views: 1462

Answers (2)

Lloyd Powell
Lloyd Powell

Reputation: 18810

In your startup, you will need to register the profile itself, I recommend that you register the Startup class so it will find all that derive from Profile in your entire project, like this:

services.AddAutoMapper(typeof(Startup));

Then you don't need the mapper configuration. Unless you have niche scenario where it's required.

Just on an additional info part, you can also call the mapper like this:

mapper.Map<Destination>(source)

As it will pick up the type of your source (unless you have polymorphism so your type is different).

Upvotes: 1

User48591
User48591

Reputation: 301

I actually ended up removing the custom member mapping and added an explicit map from the source complex type to string.

// old
CreateMap<Source, Destination>().ForMember(dest => dest.Identification, opt => opt.MapFrom(src => src.Identification.Id));

// new
CreateMap<SourceId, string>().ConvertUsing(source => source.Id);
CreateMap<Source, Destination>();

I am not sure what was missing in my initial try but this seems to do the trick.

Upvotes: 0

Related Questions