Automapper ForMember MapFrom 似乎无法正常工作

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;

destId 的值为"Source.SourceId"。基本上是 SourceId 对象的 ToString() 表示。由于某种原因,映射器未考虑单个成员映射。

在您的启动中,您将需要注册配置文件本身,我建议您注册 Startup class 这样它会在您的整个项目中找到所有派生自配置文件的内容,如下所示:

services.AddAutoMapper(typeof(Startup));

那你就不需要映射器配置了。除非你有需要它的利基场景。

就附加信息部分而言,您还可以这样调用映射器:

mapper.Map<Destination>(source)

因为它会选择你的源类型(除非你有多态性所以你的类型不同)。

实际上我最终删除了自定义成员映射并添加了一个从源复杂类型到字符串的显式映射。

// 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>();

我不确定在我最初的尝试中遗漏了什么,但这似乎可以解决问题。