Automapper禁用IgnoreMap属性一次

问题描述 投票:1回答:1

我的目标实体中有一个属性,具有IgnoreMap属性。

我想只禁用一次。我使用Automapper列表列出映射。

public class TestDto {
    public string Name { get; set; }
    public DateTime UpdateDate { get; set; }

}

public class Test {
    public string Name { get; set; }
    //Normally, I want to ignore this entities all mapping except one method.
    [IgnoreMap]
    public DateTime UpdateDate { get; set; }

}

class Program {
    public void MapMethod(List<TestDto> sourceList)
    {
        var content = new MapperConfigurationExpression();
        content.CreateMap<TestDto,Test>();
        var config = new MapperConfiguration(content);
        var mapper = config.CreateMapper();
        //I do not want to ignore UpdateDate entity in here.
        var destinationList = mapper.Map<List<Test>>(sourceList);
    }
}
c# automapper
1个回答
0
投票

你可以试试这个:

_mapper.Map<DestType>(result, options => options.AfterMap((s, d) => ((DestType) d).Code = null));

完整的例子

void Main()
{
    IConfigurationProvider conf = new MapperConfiguration(exp => exp.CreateMap<Src, Dest>());
    IMapper mapper = new Mapper(conf);

    var src = new Src(){
       Id =1,
       Name= "John Doe"
    };

    var result = mapper.Map<Dest>(src, options => options.AfterMap((s, d) => ((Dest) d).Name = null));
    result.Dump();

    var result2 = mapper.Map<List<Dest>>(srcList, options => options.AfterMap((s, d) => ((List<Dest>) d).ForEach(i => i.Name = null)));
    result2.Dump();

}

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

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

enter image description here


另外

void ConfigureMap(IMappingOperationOptions<Src, Dest> opt)
{
    opt.ConfigureMap()
        .ForMember(dest => dest.Name, m => m.Ignore());
};

 var result3 = mapper.Map<List<Dest>>(srcList, ConfigureMap());
 result3.Dump();
© www.soinside.com 2019 - 2024. All rights reserved.