AutoMapper - 如何向Profile传递参数?

4

我希望使用AutoMapper来映射我的公共数据契约和BD模型之间的关系。我需要将一个字符串参数传递给我的MapProfile,并从我的属性(在此示例中为“Code”)中获取描述。例如:

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

“从我的属性中获取描述”是什么意思? - Silly John
你的映射应该像这样:CreateMap<Source, Destination>().ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, tag))); 但是,tag 是从哪里来的呢? - Jose Alonso Monge
是的!我需要像这样的地图,我将从地图通知 _tag_。mapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag"); - Thiago Marcolino
请查看以下 https://github.com/AutoMapper/AutoMapper/issues/1005 并在您的映射中使用以下内容:CreateMap<Source, Destination>() .ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, opt.FromItems("Tag").ToString()))); 请告诉我们这是否有帮助。 - Jose Alonso Monge
2个回答

5
这可以通过使用CustomResolver来实现。
public class MyProfile : Profile
{

    protected override void Configure()
    {
        CreateMap<Destination, 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);
    }
}

5

传递键值对给Mapper

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

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

这是设置此自定义解析器映射的方法。
cfg.CreateMap<Source, Dest>()
    .ForMember(dest => dest.Foo, opt => opt.MapFrom((src, dest, destMember, context) => context.Items["Foo"]));

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

自定义值解析器是 AutoMapper 中的一个可扩展点。它们可以用来定制映射过程中如何解析源对象中的值并将其映射到目标对象中。值解析器可以对源和目标类型进行检查,并提供自定义转换逻辑以满足特定的需求。这使得 AutoMapper 可以处理各种不同类型之间的映射,例如字符串到数字,日期到时间戳等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接