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

Pup*_*kin 1 .net c# automapper

我有两个类,并使用Automapper将其映射到另一个类.例如:

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
}
Run Code Online (Sandbox Code Playgroud)

然后我使用Automapper映射SourceDestination:

cfg.CreateMap<Source, Destination>();
Run Code Online (Sandbox Code Playgroud)

它可以正常工作,但有时成员Type在课堂Source变得null.在这种情况下,我要地图成员Type在课堂上DestinationTypeId财产.这就是我想要的东西:

if Source.Type != null 
then map Destination.Type from it
else map it as 
    Destination.Type = new IdNameDest { Id = Source.Id }
Run Code Online (Sandbox Code Playgroud)

AutoMapper有可能吗?

Lee*_*nTM 6

您可以.ForMember()在声明映射时使用该方法.像这样:

cfg.CreateMap<Source, Destination>()
.ForMember(dest => dest.Type, opt => opt.MapFrom(src => src.Type != null ? src.Type : new IdNameDest { Id = src.Id }));
Run Code Online (Sandbox Code Playgroud)


Jan*_*Jan 5

虽然 LeeeonTM 的答案运行良好,但 AutoMapper 提供了一种专门的机制来替换空值。它“如果源值在成员链的任何位置都为空,则允许您为目标成员提供备用值”(摘自AutoMapper 手册)。

例子:

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