You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AutoMapper中全局禁止映射AggregateRoot子类的Timestamp属性?

解决AutoMapper全局排除AggregateRoot子类的Timestamp属性映射问题

你之前用ShouldMapProperty的方式会全局控制属性是否参与映射——不管是读取还是写入,所以把Setter设为私有后连读取映射都被禁用了,这显然不符合需求。

我们可以通过ForAllMaps做全局配置,只在目标类型是AggregateRoot的子类时忽略Timestamp属性的写入映射,这样既不影响从该属性读取映射到其他对象,也能避免往子类的Timestamp属性赋值。

实现代码

private static void AddAutoMapper(IServiceCollection services)
{
    services.AddAutoMapper(cfg =>
    {
        // 遍历所有映射规则,目标为AggregateRoot子类时忽略Timestamp
        cfg.ForAllMaps((map, exp) =>
        {
            if (typeof(AggregateRoot).IsAssignableFrom(map.DestinationType))
            {
                exp.ForMember("Timestamp", opt => opt.Ignore());
            }
        });
    }, typeof(Services).Assembly);
}

代码说明

  • ForAllMaps会遍历AutoMapper创建的所有映射规则
  • 通过typeof(AggregateRoot).IsAssignableFrom(map.DestinationType)判断当前映射的目标类型是否是AggregateRoot的子类
  • 如果匹配,就调用ForMember("Timestamp", opt => opt.Ignore())跳过该属性的写入映射
  • 这种配置下:从DTO映射到AggregateRoot子类时,Timestamp不会被赋值;但从子类映射到DTO时,Timestamp依然能正常被读取映射

如果Timestamp是特定强类型(比如byte[]),也可以通过类型匹配替代硬编码属性名,避免拼写错误:

cfg.ForAllMaps((map, exp) =>
{
    if (typeof(AggregateRoot).IsAssignableFrom(map.DestinationType))
    {
        var timestampProp = map.DestinationType.GetProperty("Timestamp");
        if (timestampProp != null && timestampProp.PropertyType == typeof(byte[]))
        {
            exp.ForMember(timestampProp.Name, opt => opt.Ignore());
        }
    }
});

内容的提问来源于stack exchange,提问作者Peter Morris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:18:27