将其他对象传递给CreateMap

时间:2016-02-16 00:05:17

标签: c# automapper

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

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 ))));
}

1 个答案:

答案 0 :(得分:3)

我担心答案是将该属性映射到AutoMapper之外。

以下是使用扩展方法执行此操作的示例,因此它仍然具有使用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);
}