如何将参数传递给配置文件?

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

我已经完成了创建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);
    }
}
链接地址: http://www.djcxy.com/p/37395.html

上一篇: How to pass parameters to Profile?

下一篇: Automapper complex types mapping exception