首页 > 解决方案 > 如果对象成员没有值,如何为对象分配 null - automapper c#

问题描述

我在 C# 中使用自动映射器。

class A 
{
   public int Value { get; set; }
   public string Code { get; set; }
   public B? Details { get; set; }
}

 class B 
 {
   public int Id { get; set;}
   public string Name { get; set; }
 } 

 class C
 {
   public int Value { get; set; }
   public string Code { get; set; }
   public int? DetailId { get; set; }
   public string? DetailName { get; set; }
 }

在自动映射器中我使用如下:

CreateMap<C, A>()
.ForPath(o => o.Details.Id, b => b.MapFrom(z => z.DetailId))
.ForPath(o => o.Details.Name, b => b.MapFrom(z => z.DetailName))
.ReverseMap();

当我使用上述映射时,我得到的输出如下

  "details ": {
        "id": 0,
        "name": ""
   }

Details如果它的成员没有值,我需要将值作为 null 而不是对象类型。即)DetailId并且DetailName没有价值。如何得到这个?

  "details" : null

标签: c#automapper

解决方案


您可以使用条件映射

    var config = new MapperConfiguration(cfg =>
      {
         cfg.CreateMap<C, B>()
            .ForMember(o => o.Id, b => b.MapFrom(z => z.DetailId))
            .ForMember(o => o.Name, b => b.MapFrom(z => z.DetailName));

          cfg.CreateMap<C, A>()
             .ForMember(o => o.Details, b => b.MapFrom((c, a, obj, context) => !string.IsNullOrEmpty(c.DetailName) ? context.Mapper.Map<B>(c) : null))
             .ReverseMap();
      });
    

推荐阅读