C# AutoMapper 使用方法总结

2020-06-15 17:00:09王振洲

3.2 配置可见性

默认情况下,AutoMapper 仅映射 public 成员,但其实它是可以映射到 private 属性的。

var config = new MapperConfiguration(cfg =>
{
 cfg.ShouldMapProperty = p => p.GetMethod.IsPublic || p.SetMethod.IsPrivate;
 cfg.CreateMap<Source, Destination>();
});

需要注意的是,这里属性必须添加 private set,省略 set 是不行的。

3.3 全局属性/字段过滤

默认情况下,AutoMapper 尝试映射每个公共属性/字段。以下配置将忽略字段映射。

var config = new MapperConfiguration(cfg =>
{
	cfg.ShouldMapField = fi => false;
});

3.4 识别前缀和后缀

var config = new MapperConfiguration(cfg =>
{
 cfg.RecognizePrefixes("My");
 cfg.RecognizePostfixes("My");
}

3.5 替换字符

var config = new MapperConfiguration(cfg =>
{
 cfg.ReplaceMemberName("Ä", "A");
});

这功能我们基本上用不上。

4 调用构造函数

有些类,属性的 set 方法是私有的。

public class Commodity
{
 public string Name { get; set; }

 public int Price { get; set; }
}

public class CommodityDto
{
 public string Name { get; }

 public int Price { get; }

 public CommodityDto(string name, int price)
 {
  Name = name;
  Price = price * 2;
 }
}

AutoMapper 会自动找到相应的构造函数调用。如果在构造函数中对参数做一些改变的话,其改变会反应在映射结果中。如上例,映射后 Price 会乘 2。

禁用构造函数映射:

public class Commodity
{
 public string Name { get; set; }

 public int Price { get; set; }
}

public class CommodityDto
{
 public string Name { get; }

 public int Price { get; }

 public CommodityDto(string name, int price)
 {
  Name = name;
  Price = price * 2;
 }
}

AutoMapper 会自动找到相应的构造函数调用。如果在构造函数中对参数做一些改变的话,其改变会反应在映射结果中。如上例,映射后 Price 会乘 2。

禁用构造函数映射:

var config = new MapperConfiguration(cfg => cfg.DisableConstructorMapping());

禁用构造函数映射的话,目标类要有一个无参构造函数。

5 数组和列表映射

数组和列表的映射比较简单,仅需配置元素类型,定义简单类型如下:

public class Source
{
 public int Value { get; set; }
}

public class Destination
{
 public int Value { get; set; }
}

映射:

var config = new MapperConfiguration(cfg =>
{
 cfg.CreateMap<Source, Destination>();
});
IMapper mapper = config.CreateMapper();

var sources = new[]
{
 new Source { Value = 5 },
 new Source { Value = 6 },
 new Source { Value = 7 }
};

IEnumerable<Destination> ienumerableDest = mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = mapper.Map<Source[], ICollection<Destination>>(sources);
IList<Destination> ilistDest = mapper.Map<Source[], IList<Destination>>(sources);
List<Destination> listDest = mapper.Map<Source[], List<Destination>>(sources);
Destination[] arrayDest = mapper.Map<Source[], Destination[]>(sources);