Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapping - for IEnumerable map multiple properties with different name

Tags:

c#

automapper

I have two class Say:

  public class SourceData
        {
            public string SourceCode { get; set; }        
            public string SourceName { get; set; }
        }

and

public class DestData
    {
        public string Code { get; set; }
        public string DestName { get; set; }
    }

I try to map IEnumerable of SourceData to DestData, but it is not working

I try with

AutoMapper.Mapper.CreateMap<IEnumerable<SourceData >, IEnumerable<DestData>>()
like image 965
111 Avatar asked Apr 19 '26 16:04

111


2 Answers

Both classes have fields with different names. AutoMapper won't pick them up automatically. So you need to explicitly tell it how to map fields in both classes. You do this like this.

Mapper.CreateMap<SourceData, DestData>()
   .ForMember(dest => dest.DestName, a => a.MapFrom(src => src.SourceName))
   .ForMember(dest => dest.Code, a => a.MapFrom(src => src.SourceCode))

Note that you're creating maps between types themselves not between collections of types as AutoMapper will automatically handle collections. Next just use following to map:

var destList= Mapper.Map<List<DestData>>(sourceList);

or

Mapper.Map<List<SourceData>, List<DestData>>(sourceList, destList);

depending on your situation.

like image 74
Shoaib Shakeel Avatar answered Apr 22 '26 05:04

Shoaib Shakeel


Mapper.Map>(someDataEnum)Have you mapped SourceData to DestData? You don't have to map collections.

var configuration = Mapper.Configuration;

configuration.CreateMap<SourceData, DestData>()
    .ForMember(lite => lite.Code, src => src.MapFrom(post => post.SourceCode))
    .ForMember(lite => lite.DestName, src => src.MapFrom(post => post.SourceName))

and to map

var destDataCollection= Mapper.Map<IEnumerable<SourceData>, IEnumerable<DestData>>(sourceDataCollection);
like image 39
Artiom Avatar answered Apr 22 '26 06:04

Artiom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!