简体   繁体   中英

AutoMapper ignore properties while mapping a list

Is it possible in AutoMapper to ignore certain properties while mapping a list? For example, I have two classes Metadata and MetadataInput.

Both have the same fields except for destination, "MetadataInput", which has an extra field.

Mapper.CreateMap <IList<Metadata>, IList<MetadataInput>>()

I've tried to use the formember option but it generates errors, probably because the property cannot be used when you want to map a list? If yes, is there alternative solution?

As Darin Dimitrov suggested, you should not try and map lists or collections.

If you have a 1 -> 1 relationship between them all, just make a map like:

Mapper.CreateMap<Metadata, MetadataInput>().ForMember(s => s.Property, t => t.Ignore());

Then you could use your list and select it to the other list.

var metadataList = new List<Metadata>();

var meatadataInputList = metadataList.Select(p => Mapper.Map<MetadataInput>(p).ToList();

Thanks for the useful comments. Because both lists are already made before mapping I've done it this way:

Gets the list from the db:

List<Metadata> metadatas = _Metadataservice.GetList(_Collectionservice.Get("Koekelare").ID).ToList();

Create the mapper (thanks for pointing out my mistake):

Mapper.CreateMap<Metadata, MetadataInput>().ForMember(s => s.Property, t => t.Ignore());

Make a new list and map the new (single) values one by one:

List<MetadataInput> meta = new List<MetadataInput>();
for (int i = 0; i < e.Count; i++)
{
  meta.Add(Mapper.Map<Metadata, MetadataInput>(metadatas[i], input.Metadatas[i]));
}

Could someone confirm this is a good way?

Use this mapper configuration to get the desired result:

Mapper.CreateMap<Output, Input>().ForMember(s => s.InputProperty1, t => t.Ignore());
Mapper.CreateMap<Output, Input>().ForMember(s => s.InputProperty2, t => t.Ignore());
Mapper.CreateMap<Input, Output>();
listOfItems = Mapper.Map<List<Input>, List<Output>>(InputListObject);

As others suggested, we should avoid mapping lists and collections. In order to ignore all the unmapped properties, the following worked out for me.

 CreateMap<Metadata, MetadataInput>()
        .ForMember(dest => dest.Id, o => o.MapFrom(src => src.sourceIdentifier))
        .ForMember(dest => dest.Name, o => o.MapFrom(src => src.sourceName))
        .ForAllOtherMembers(opts => opts.Ignore());

ForAllOtherMembers should be the last in the method chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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