使用Automapper更新集合是指在自定义映射时,需要同时更新现有集合中的项。为实现这一目的,可使用Automapper的自定义映射功能,并使用AddCollectionMapping()方法。下面是一个示例代码:
//定义对象模型
public class Source
{
public ICollection
public class Destination { public string Name { get; set; } }
//定义自定义映射
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap
var mapper = config.CreateMapper();
//测试代码
var source = new Source
{
Destinations = new List
var destination = new Source
{
Destinations = new List
//调用Mapper mapper.Map(source, destination);
//输出测试结果 foreach (var item in destination.Destinations) { Console.WriteLine(item.Name); }
输出结果为: Destination 1 Destination 2
可以看到,使用自定义映射更新集合时,现有集合的项并未被覆盖。
上一篇:Automapper:System.InvalidOperationException:'Coalesceusedwithtypethatcannotbenull'
下一篇:AutoMapperAllowAdditiveTypeMapCreationdoesn'tmergemappings