在Automapper中,我们可以使用ReverseMap()方法来创建一个反向映射。如果在反向映射中,我们想要忽略某些目标属性,可以使用该属性的Ignore()方法。
示例代码如下:
public class Source { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } }
public class Destination { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Other { get; set; } // 需要忽略的属性 }
// 创建映射配置
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap
// 创建映射 var mapper = configuration.CreateMapper();
// 映射实例
var source = new Source { Id = 1, Name = "John", Description = "Description" };
var destination = mapper.Map
// 显示目的对象 Console.WriteLine(destination.Id); // 输出:1 Console.WriteLine(destination.Name); // 输出:John Console.WriteLine(destination.Description); // 输出:Description Console.WriteLine(destination.Other); // 输出:null