How to pass parameters to Profile?
I'd like to use automapper to map between my public data contracts and my BD model. And I need to pass a string parameter into my MapProfile and get a description from my property ("Code" in this example). For example:
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/37396.html
上一篇: 使AutoMapper自动映射前缀属性
下一篇: 如何将参数传递给配置文件?