我想使用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);
}
}
答案 0 :(得分:3)
我已经创建了 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);
}
}