0
votes

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?

4
Normally you should never map lists or collections. You map the classes and AutoMapper takes care of the rest.Darin Dimitrov
Try Mapper.CreateMap <Metadata, MetadataInput>() and add it into listMurali Murugesan

4 Answers

1
votes

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();
1
votes

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);
1
votes

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.

0
votes

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?