我希望使用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);
}
}
CreateMap<Source, Destination>().ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, tag)));
但是,tag 是从哪里来的呢? - Jose Alonso Mongemapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag");
- Thiago MarcolinoCreateMap<Source, Destination>() .ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, opt.FromItems("Tag").ToString())));
请告诉我们这是否有帮助。 - Jose Alonso Monge