在 .Net Core 项目中使用 AutoMapper 时 ForMember 设置不起作用

ForMember setting does not working when using AutoMapper in .Net Core project

我在我的 .NET Core 项目中使用 AutoMapper。默认的 mapper 函数运行良好,但是当我在 myProfile.cs class 中使用 .ForMember() 时,它不起作用。

myProfile.cs 就像:

public class ServiceProfile : Profile
{
    public ServiceProfile()
    {
        CreateMap<Organization, OrganizationDto>()
            .ForMember(x => x.Active, opt => opt.MapFrom(src => src.Disabled));
    }
}

startup.cs中的配置是这样的:

public void ConfigureServices(IServiceCollection services)
{

    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new ServiceProfile());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

    services.AddMvc();
}

然后

input.Disabled=0;
var output = _mapper.Map<Organization>(input);

我希望 output.Active 为 0,但实际输出为空。

更新:

不好意思,方法没问题,因为我用的是dapper,跳过了map步骤

可能是因为映射方法是CreateMap<TSource, TDestination>,源是第一个泛型参数,但在下面的代码中,您的映射是从 DTO class 到组织 class(在另一个方向)可能没有指定映射。

您可能还需要为从 OrganizationDtoOrganization 的另一个方向创建映射。

更新:现在有一种简单的方法可以通过将 .ReverseMap() 添加到 CreateMap 调用链的末尾来为另一个方向添加映射。