简体   繁体   English

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

[英]Automapper options.ignore() does not work for lists

.ForMember(c = c.Property, options => options.Ignore()) works when you use a single object to map. .ForMember(c = c.Property, options => options.Ignore())在使用单个对象进行映射时起作用。 However, the ignore does not work in the case of lists. 但是,对于列表,忽略不起作用。 For example see below code where destination List object already has some entries and when mapping, i want to ignore a specific property as per the created map. 例如,请参见下面的代码,其中目标列表对象已经具有一些条目,并且在映射时,我想根据创建的映射忽略特定的属性。 When the mapping happens, the ignore rules do not apply and the value gets set from source only 发生映射时,忽略规则不适用,并且仅从源设置值

//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);

//now in the destCust instance, i expect Next to persist the value "Hrishi" based on options.ignore for property Next.. but it does not happen. //现在在destCust实例中,我希望Next保留基于属性Next ..的options.ignore的值“ Hrishi”。但是不会发生。 this value gets set to null. 该值设置为null。

In that sentence: 在那句话中:

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

Automapper is creating a new instance of List<Customer2> and asigning it to destList , so the previous object is not available anymore. Automapper正在创建List<Customer2>的新实例,并将其分配给destList ,因此先前的对象不再可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM