How to use AutoMapper .ForMember?

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

I am trying to set up AutoMapper to convert from Entity to DTO. I know I'm supposed to be using .ForMember() after Mapper.CreateMap(),> to set up custom mappings, but this doesn't seem to be an available method.

Edit for clarification: I am not looking for a link to the documentation, which I have read, or an explanation of the basic syntax. I am using the correct syntax as described in answers and the documentation, for example:

Mapper.CreateMap()       .ForMember(dest => dest.Code, opt => opt.MapFrom(src => src.Name));,>

If I have an invalid type name within CreateMap<> I can see "ForMember" as a valid method, mousing over shows the method signature as I would normally expect. But as soon as I give it two valid types, ForMember says it cannot resolve the symbol, as if the method is not available.

Is there some kind of constraint on the generic classes which I am not meeting?

Thanks

回答1:

Try the following syntax:

Mapper     .CreateMap()     .ForMember(         dest => dest.SomeDestinationProperty,         opt => opt.MapFrom(src => src.SomeSourceProperty)     );,>

or if the source and destination properties have the same names simply:

Mapper.CreateMap();,>

Please checkout the relevant sections of the documentation for more details and other mapping scenarios.



回答2:

In the end, I believe this turned out to be some kind of incompatibility with ReSharper.

ReSharper seems to have caused Automapper code to display incorrectly, but work just fine (even though it displays red with error messages). Uninstalling ReSharper fixed this issue completely.



回答3:

a sample implementation would be as follows:

Mapper.CreateMap()   .ForMember(m => m.GameType, opt => opt.MapFrom(src => src.Type)),>

We need to map this property since the names of the properties of Game and GameViewModel are different - if they are the same and of the same type then it will not need a ForMember

another use of the ForMember is to Ignore Mappings

Mapper.CreateMap()     .ForMember(dest => dest.Prize, opt => opt.Ignore());,>


回答4:

Are you doing it like this

Mapper.CreateMap().ForMember(What ever mapping in here),destinationtype>

This page has some good examples



转载请标明出处:How to use AutoMapper .ForMember?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!