Automapper. 如果源成员为null,则映射。

5
我有两个类,使用自动映射器将一个映射到另一个。例如:
public class Source 
{
    // IdName is a simple class containing two fields: Id (int) and Name (string)
    public IdName Type { get; set; } 

    public int TypeId {get; set; }

    // another members
}

public class Destination
{
    // IdNameDest is a simple class such as IdName
    public IdNameDest Type { get; set; } 

    // another members
}

然后我使用Automapper将Source映射到Destination

cfg.CreateMap<Source, Destination>();

它运行正常,但有时类Source中成员Type会变为null。在这种情况下,我想从TypeId属性将类Destination中的成员Type映射过来。这就是我想要的。

if Source.Type != null 
then map Destination.Type from it
else map it as 
    Destination.Type = new IdNameDest { Id = Source.Id }

使用AutoMapper进行这种操作是否可行呢?

这个 https://dev59.com/_WDVa4cB1Zd3GeqPbDiw#9205604 有帮助吗? - mjwills
4个回答

7
您可以在声明映射时使用 .ForMember() 方法。例如:
cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id }));

1
很棒的答案,伙计。 - Hatted Rooster

5

尽管Leeeon的答案可以正常工作,但AutoMapper提供了一种专门的机制来替换null值。如果源值在成员链中的任何位置为null,则它“允许您为目标成员提供替代值”(摘自AutoMapper手册)。

示例:

cfg.CreateMap<Source, Destination>()
    .ForMember(dest => dest.Value, opt => opt.NullSubstitute(new IdNameDest { Id = src.Id }));

1
使用C# 6.0,可以使用空值合并运算符。
cfg.CreateMap<Source, Destination>()
   .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type ?? new IdNameDest { Id = src.Id }));

0

我使用映射解析器成功解决了这个问题。

public class SomeResolver : IValueResolver<Soruce, Dest, Guid>
{
    public Guid Resolve(Source source, Dest destination, Guid, destMember, ResolutionContext context)
    {
       
        destination.Value= source.Value!=null ? source.Value:0;

        return destination.MainGuid = Guid.NewGuid();
    }
}

然后在映射配置上

       CreateMap<BioTimeEmployeeSummaryDTO, BioTimeEmployeeAttendanceSummary>()
         
            
            .ForMember(dest => dest.MainGuid, opt => opt.MapFrom<YourResolverClass>())

            .ReverseMap();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接