Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

.net - How to use AutoMapper .ForMember?

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<Entity, DTO>() 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<EFAddress, Address>()
      .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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try the following syntax:

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

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

Mapper.CreateMap<Entity, EntityDto>();

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...