AutoMapper - 如何将参数传递给 Profile?

Thi*_*ino 3 c# automapper

我想使用 automapper 在我的公共数据合同和我的 BD 模型之间进行映射。我需要将一个字符串参数传递到我的 MapProfile 并从我的属性中获取描述(在本例中为“代码”)。例如:

public class Source
{
    public int Code { get; set; }
}

public class Destination
{
    public string Description { get; set; }
}

public class Dic
{
    public static string GetDescription(int code, string tag)
    {
            //do something
            return "My Description";
    }
}

public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destination, Source>()
            .ForMember(dest => dest.Description, 
                opt => /* something */ 
                Dic.GetDescription(code, tag));
    }
}

public class MyTest 
{

        [Fact]
        public void test()
        {
            var source = new Source { Code = 1};

            var mapperConfig = new MapperConfiguration(config => config.AddProfile<MyProfile>());
            var mapper = mapperConfig.CreateMapper();

            var result = mapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag");

            Assert.Equal("My Description", result.Description);
        }
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ino 5

我已经创建了一个CustomResolver

public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destinantion, Source>()
            .ForMember(dest => dest.Description, opt => opt.ResolveUsing<CustomResolver>().FromMember(src => src.Code));
    }
}

public class CustomResolver : IValueResolver
{
    public ResolutionResult Resolve(ResolutionResult source)
    {
        var code = (int)source.Value;

        var tag = source.Context.Options.Items["Tag"].ToString();

        var description = Dic.GetDescription(code, tag);

        return source.New(description);
    }
}
Run Code Online (Sandbox Code Playgroud)


A.R*_*R.B 5

将键值传递给Mapper

调用映射时,您可以使用键值传递额外的对象,并使用自定义解析器从上下文中获取对象。

mapper.Map<Source, Dest>(src, opt => opt.Items["Foo"] = "Bar");
Run Code Online (Sandbox Code Playgroud)

这是为此自定义解析器设置映射的方法

cfg.CreateMap<Source, Dest>()
    .ForMember(dest => dest.Foo, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["Foo"]));
Run Code Online (Sandbox Code Playgroud)

来自: https: //docs.automapper.org/en/stable/Custom-value-resolvers.html