将其他对象传递给 CreateMap

本文关键字:CreateMap 其他 对象 | 更新日期: 2023-09-27 18:34:40

我的对象映射要求我传递源对象和其他对象,以便能够适当地映射目标对象。但是,我无法确定能够完成这项工作的方法。

public class SourceDto
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string SourceValue3 { get; set; }
    public string SourceValue4 { get; set; }
}
public class AnotherSourceDto
{
    public string AnotherSourceValue1 { get; set; }
    public string AnotherSourceValue2 { get; set; }
    public string AnotherSourceValue3 { get; set; }
    public string AnotherSourceValue4 { get; set; }
}
public class Destination
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string DestValue3 { get; set; }
}
public string ConvertToDestValue3(string sourceValue3, string anotherSourceValue2)
{
    // Some logic goes here
    return sourceValue3 + " " + anotherSourceValue2;
}

void Main()
{
    var config = new MapperConfiguration(
    cfg =>cfg.CreateMap<SourceDto, Destination>()
    .ForMember(dest => dest.DestValue3, 
    opt => opt.MapFrom(
        src => ConvertToDestValue3(src.SourceValue3, "" //Here I need to pass AnotherSourceDto.AnotherSourceValue2 ))));
}

将其他对象传递给 CreateMap

怕答案是在AutoMapper之外映射该属性。

下面是一个示例,您可以使用扩展方法执行此操作,因此它仍然具有使用自动映射器完成的外观和感觉。

// put inside a static class
public static Destination CustomMap(
    this IMapper mapper,
    SourceDto source,
    AnotherSourceDto anotherSource)
{
    var destination = mapper.Map<Destination>(source);
    destination.DestValue3 =
        source.SourceValue3 + " " + anotherSource.AnotherSourceValue2;
    return destination;
}
void Main()
{
    var config = new MapperConfiguration(cfg =>
        cfg.CreateMap<SourceDto, Destination>()
            .ForMember(dest => dest.DestValue3, opt => opt.Ignore()));
    // usage
    var mapper = config.CreateMapper();
    var source = new SourceDto { /* add properties */ };
    var anotherSource = new AnotherSourceDto { /* add properties */ };
    var destination = mapper.CustomMap(source, anotherSource);
}