【发布时间】:2022-10-15 01:31:14
【问题描述】:
楷模
public class NodeInfo
{
public double X { get; set; }
}
public class NetNode
{
public double X { get; set; }
}
对于上面的模型,我有下面的地图。假设源对象的“X”属性的值为 5。我希望“o”的值为 5,但它始终为 0。如果我返回“s.X”而不是“o”,它可以正常工作,但我认为 TMember 也应该返回相应的属性值。
映射器配置文件
public class ProfileBase : Profile
{
public ProfileBase()
{
CreateMap<NodeInfo, NetNode>()
.ForMember(n => n.X, opt => opt.MapFrom((s, d, o, ctx) => o)).ReverseMap();
}
}
我为上面的映射使用了以下重载。
IMemberConfigurationExpression<TSource, TDestination, TMember>
MapFrom<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> mappingFunction);
执行
var config = new MapperConfiguration(cfg => {
cfg.AddProfile(new ProfileBase());
});
IMapper mapper = config.CreateMapper();
NodeInfo nodeInfo = new() { X = 5 };
NetNode netNode;
netNode = mapper.Map<NetNode>(nodeInfo);
//netNode.X should be 5 but it is 0
//change the "=> o" in the profile to "=> s.X" and it returns 5
【问题讨论】:
-
试试docs.automapper.org/en/latest/Value-converters.html。您将在那里拥有源成员。
标签: c# .net mapping automapper