【问题标题】:How to configure Automapper to ignore Object-Properties if properties is null but map if not null如果属性为空,如何将 Automapper 配置为忽略对象属性但如果不为空则映射
【发布时间】:2020-08-05 13:37:14
【问题描述】:

我正在使用 Automapper。在那里,我将 DTO 对象映射到另一个对象。

UserProperties 类。

public string DisplayName { get; set; }

public int Id { get; set; }

public int NotesCount {get;set;}

PersonsDTO 类

public string UserName { get; set; }

public int UserId { get; set; }

public int NotesCount { get ; set; }

public int BooksCount { get; set; }

人物类

public UserProperties? UserDetails { get; set; }

public int NotesCount { get ; set; }

public int BooksCount { get; set; }

在映射配置文件中,

CreateMap<PersonsDTO, Persons>()
             .ForPath(o => o.UserDetails.DisplayName, b => b.MapFrom(z => z.UserName))
             .ForPath(o => o.UserDetails.Id, b => b.MapFrom(z => z.UserId))
             .ReverseMap();

就我而言,Persons 类中的UserDetails 是可空类型。如果PeronsDTO 类中的UserId0 表示,我不需要映射UserDetails。对于 UserDetails 属性,它应该返回 null。

我怎样才能实现它?

自动映射器版本:9.0.0

【问题讨论】:

标签: c# lambda automapper


【解决方案1】:

您可以指定一个自定义解析器来显式执行您的自定义映射。

    CreateMap<PersonDTO, Person>()
      .ForMember(dest => dest.UserDetails, opt => opt.MapFrom<CustomResolver>());

    public class CustomResolver : IValueResolver<PersonDTO, Person, UserProperties>
    {
        public UserProperties Resolve(PersonDTO source, Person destination, UserProperties member, ResolutionContext context)
        {
            if (source.UserId == 0)
                return null;
            return new UserProperties
            {
                DisplayName = source.UserName,
                Id = source.UserId
            };
        }
    }

【讨论】:

  • 是的,尝试添加这样的条件......但它不起作用。
  • 如果它们不起作用,您能告诉我您从我的建议中看到的行为吗?如果条件不满足,条件语句应该阻止映射发生
  • 上述条件语句应该只阻止像 UserDetails.DisplayName 这样的内部属性的映射。我需要防止 UserDetails 类本身的映射。
  • 我将答案改为使用自定义解析器。
猜你喜欢
  • 1970-01-01
  • 2017-08-08
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 2017-12-31
  • 1970-01-01
相关资源
最近更新 更多