简体   繁体   中英

Unable to map fields with different names using Automapper ForMember method

I am looking to map a entity named PortalUser to another entity named UserFacade, both of them have same fields except one because name of the field is different in both classes.

After a bit of googling I found out a way of mapping fields with different name to each other as stated here How to specify mapping rule when names of properties differ

The solution is to use ForMember function and explicitly define which field to map like stated in answer of question above.

My problem is that ForMember isn't working to way it is explained in almost every answer at stackoverflow

AutoMapper.Mapper.CreateMap(user.GetType(), typeof(UserFacade))
    .ForMember(dest => dest.PortalRole, opt => opt.MapFrom(src => src.Role);

var userFacade = AutoMapper.Mapper.Map<UserFacade>(user);

The 2nd line at ForMember says that cannot convert lambda to string type. The ForMember function is used the same way in almost every answer at stackoverflow, but it doesn't seem to work here, kindly help.

Try like below:

AutoMapper.Mapper.CreateMap(user.GetType(), typeof(UserFacade))
    .ForMember(dest => dest.PortalRole, opt => opt.MapFrom(src => src.Role));

Also can you confirm, this is added to namespace:

    using System.Linq;

When I look at this. I see 3 possible reasons :

1) Typo in the question :

AutoMapper.Mapper.CreateMap(user.GetType(), typeof(UserFacade))
    .ForMember(dest => dest.PortalRole, opt => opt.MapFrom(src => src.Role));

2) usings

using AutoMapper;
using System.Linq;

3) no mapper for Role to PortalRole.

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