【发布时间】: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<Source, Destination>().ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, tag)));但是,tag 来自哪里? -
是的!我需要这样的地图,我会从地图
mapper.Map<Destination>(source, opt => opt.Items["Tag"] = "AnyTag");通知tag -
看看这个github.com/AutoMapper/AutoMapper/issues/1005并在你的映射中使用它:
CreateMap<Source, Destination>() .ForMember(dest => dest.Description, opt => opt.MapFrom(s => Dic.GetDescription(s.Code, opt.FromItems("Tag").ToString())));告诉我们这是否对你有帮助
标签: c# automapper