Automapper options.ignore()不适用于列表

时间:2014-06-25 13:30:23

标签: c# .net automapper automapper-2 automapper-3

使用单个对象进行映射时,

.ForMember(c = c.Property, options => options.Ignore())可以正常工作。  但是,忽略在列表的情况下不起作用。  例如,请参阅下面的代码,其中目标List对象已经有一些条目,并且在映射时,我想根据创建的映射忽略特定属性。  映射发生时,忽略规则不适用,值仅从源设置

//class definition
 public class Customer
 {
 public int MyProperty { get; set; }
 public string Next { get; set; }
 }
 public class Customer2
 {
 public int MyProperty { get; set; }
 public string Next { get; set; }
 }

//create map where Next property is to be ignored
 AutoMapper.Mapper.CreateMap()
    .ForMember(c=> c.Next, options => options.Ignore());

//create and populate source list and dest list
 var sourceCust = new Customer() { MyProperty = 1, Next = string.Empty };
 var destCust = new Customer2() { MyProperty = 0, Next = "Hrishi" };
 var sourceList = new List<Customer>();
 sourceList.Add(sourceCust);

 var destList = new List<Customer2>();
 destList.Add(destCust);


//do the mapping
 destList = AutoMapper.Mapper.Map, List>(sourceList);

//现在在destCust实例中,我希望Next基于options.ignore属性Next持久保存值“Hrishi”但是它不会发生。此值设置为null。

1 个答案:

答案 0 :(得分:0)

在那句话中:

destList = AutoMapper.Mapper.Map, List>(sourceList);

Automapper正在创建List<Customer2>的新实例并将其设置为destList,因此之前的对象不再可用。