【问题标题】:Automapper TMember doesn't get the expected valueAutomapper TMember 没有得到预期值
【发布时间】: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

【问题讨论】:

标签: c# .net mapping automapper


【解决方案1】:

TMember 代表目标对象的目标成员,即新实例化的NetNode 实例的X 属性的0 值。

来自GitHub 的文档:

使用自定义函数映射目标成员。
访问源、目标对象,目的地成员, 和 语境。

/// <summary>
/// Map destination member using a custom function. Access the source, destination object, destination member, and context.
/// </summary>
/// <remarks>Not used for LINQ projection (ProjectTo)</remarks>
/// <param name="mappingFunction">Function to map to destination member</param>
void MapFrom<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> mappingFunction);

【讨论】:

    猜你喜欢
    • 2022-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2014-05-14
    • 2021-12-10
    相关资源
    最近更新 更多