如何使用.NET Automapper的ValueResolver? (从Automapper的v3更新到v6)

时间:2018-02-12 07:19:17

标签: c# .net automapper

我正在使用Automapper v 3.3.1更新一个旧项目,直至(当前最新的)v 6.2.2

我有一个自定义解析器,现在无法编译。我不确定如何重构它,使用较新版本的ValueResolver

当前代码

CreateMap<TwitterShareJsonModel, Tweet>()
    .ForMember(dest => dest.Content, opt => opt.ResolveUsing<ShareContentResolver>());

...

public class ShareContentResolver : IValueResolver<SharingJsonModelBase, ShareContent>
{
    protected override ShareContent ResolveCore(SharingJsonModelBase source)
    {
        if (source.Post == null &&
            source.Profile == null)
        {
            throw new InvalidOperationException("Must have a Post or Profile shared.");
        }

        return source.Post != null
            ? (ShareContent) Map<SharingPostJsonModel, SharePost>(source.Post)
            : Map<SharingProfileJsonModel, ShareProfile>(source.Profile);
    }
}

我注意到我需要将继承更改为IValueResolver(现在需要三种输入类型)。

1 个答案:

答案 0 :(得分:0)

在AutoMapper文档中,IValueResolver具有以下定义

public interface IValueResolver<in TSource, in TDestination, TDestMember>
{
    TDestMember Resolve(TSource source, TDestination destination, TDestMember destMember, ResolutionContext context);
}

如果我们考虑以下内容,

public class Source
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
}

public class Destination
{
    public int Total { get; set; }
}

CustomResolver将Total字段映射到Value1和Value2的总和,

public class CustomResolver : IValueResolver<Source, Destination, int>
{
    public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
    {
        return source.Value1 + source.Value2;
    }
}

用法

Mapper.Initialize(cfg =>
   cfg.CreateMap<Source, Destination>()
     .ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>());
Mapper.AssertConfigurationIsValid();

var source = new Source
    {
        Value1 = 5,
        Value2 = 7
    };

var result = Mapper.Map<Source, Destination>(source);

result.Total.ShouldEqual(12);