automapper:mapping依赖于其他属性

时间:2013-01-25 06:21:54

标签: c# automapper

我有两个对象:

public class Info
{
   public string ArtificialPerson {get; set;}
   ...
}

public class DtoInfo
{
   public string FullName {get; set;}
   public bool IsLegal {get; set;}
}

如果IsLegal为真,我想执行以下操作,然后将FullName映射到ArtificialPerson。我怎么能这样做?
谢谢

1 个答案:

答案 0 :(得分:3)

您应该设置一些映射配置:

        Mapper.CreateMap<DtoInfo, Info>().ForMember(info => info.ArtificialPerson, configExpr => 
        { 
            configExpr.MapFrom(dtoInfo => dtoInfo.FullName);
            configExpr.Condition((DtoInfo dtoInfo) => dtoInfo.IsLegal);
        });

        var info1 = Mapper.Map<Info>(new DtoInfo
        {
            FullName = "Lemons",
            IsLegal = true
        });

        Console.WriteLine(info1.ArtificialPerson); // displays "Lemons"

        var info2 = Mapper.Map<Info>(new DtoInfo
        {
            FullName = "Cocaine",
            IsLegal = false
        });

        Console.WriteLine(info2.ArtificialPerson); // displays null string