【问题标题】:AutoMapper - How to pass parameters to Profile?AutoMapper - 如何将参数传递给配置文件?
【发布时间】:2016-10-10 18:49:09
【问题描述】:

我想使用 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);
        }
}

【问题讨论】:

  • “从我的财产获取描述”是什么意思?
  • 您的地图需要如下所示:CreateMap&lt;Source, Destination&gt;().ForMember(dest =&gt; dest.Description, opt =&gt; opt.MapFrom(s =&gt; Dic.GetDescription(s.Code, tag))); 但是,tag 来自哪里?
  • 是的!我需要这样的地图,我会从地图mapper.Map&lt;Destination&gt;(source, opt =&gt; opt.Items["Tag"] = "AnyTag"); 通知tag
  • 看看这个github.com/AutoMapper/AutoMapper/issues/1005并在你的映射中使用它:CreateMap&lt;Source, Destination&gt;() .ForMember(dest =&gt; dest.Description, opt =&gt; opt.MapFrom(s =&gt; Dic.GetDescription(s.Code, opt.FromItems("Tag").ToString())));告诉我们这是否对你有帮助

标签: c# automapper


【解决方案1】:

我已经创建了一个 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);
    }
}

【讨论】:

    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多