简体   繁体   English

使用Automapper ForMember方法无法映射具有不同名称的字段

[英]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. 我希望将一个名为PortalUser的实体映射到另一个名为UserFacade的实体,它们两个都具有相同的字段,但是一个字段相同,因为两个类的字段名称都不相同。

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. 解决方案是使用ForMember函数并明确定义要映射的字段,如上面问题的回答中所述。

My problem is that ForMember isn't working to way it is explained in almost every answer at stackoverflow 我的问题是,ForMember无法按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. ForMember的第二行表示无法将lambda转换为字符串类型。 The ForMember function is used the same way in almost every answer at stackoverflow, but it doesn't seem to work here, kindly help. ForMember函数在stackoverflow的几乎每个答案中都以相同的方式使用,但是在这里似乎不起作用,请帮忙。

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 : 我看到3个可能的原因:

1) Typo in the question : 1)错字问题:

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

2) usings 2)使用

using AutoMapper;
using System.Linq;

3) no mapper for Role to PortalRole. 3)没有角色映射到PortalRole。

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

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