2

我有以下源和目标对象:

public class Source
{       
    public string Value1{ get; set; }

}

public class Destination 
{
    public string Value1{ get; set; }
    public int Ranking { get; set; }
}

我正在尝试将 Source 的集合对象映射到目标的 Collection 对象。我的源集合是这样的:

var source = new List<Source>();
source.Add(new Source(){ Value1= "test1" });
source.Add(new Source(){ Value1= "test2" });

如果目标对象中的 Ranking 属性应该对应于源集合中的项目索引,我该如何编写映射器?

即在映射目的地排名后SourceValue1 = "test1"将是1,下一个将是2

4

2 回答 2

2

在地图操作之前和之后使用(请参阅 文档):

var source = new List<Source>();
source.Add(new Source() { Value1 = "test1" });
source.Add(new Source() { Value1 = "test2" });

Mapper.Initialize(config =>
{
    config.CreateMap<Source, Destination>();
});

var destinations = source.Select(x => Mapper.Map<Source, Destination>(x, opt => {
    opt.AfterMap((src, dest) => dest.Ranking = source.IndexOf(x) + 1);
}));
于 2016-10-16T03:57:58.097 回答
1

您可以通过几种方式做到这一点,但如果您希望您的转换器单元可测试,我建议使用继承自ITyperConverter<TSource, TDestination>.

转换类:

public class SourceToDestinationConverter : ITypeConverter<Source, Destination>
{
    private int currentRank;
    public SourceToDestinationConverter(int rank)
    {
        currentRank = rank;
    }

    public Destination Convert(Source source, Destination destination, ResolutionContext context)
    {
        destination = new Destination
        {
            Value1 = source.Value1,
            Ranking = currentRank
        };
        return destination;
    }
}

将您的课程设置为 Mapper 配置:

Mapper.Initialize(config =>
{
        config.CreateMap<Source, Destination>().ConvertUsing<SourceToDestinationConverter>();
});
Mapper.AssertConfigurationIsValid();

调用方法:

var sources = new List<Source>{
    new Source() { Value1 = "test1" },
    new Source() { Value1 = "test2" }
};

var destinationsRanked = sources.Select(s => Mapper.Map<Source, Destination>(s, options => options.ConstructServicesUsing(
        type => new SourceToDestinationConverter((source.IndexOf(s) + 1))
)));

结果最终成为。

Value1 | Ranking
test1  | 1
test2  | 2
于 2016-10-16T04:00:35.093 回答