How to use AutoMapper .ForMember?

后端 未结 5 1288
野性不改
野性不改 2020-12-04 15:10

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()<

相关标签:
5条回答
  • 2020-12-04 15:28

    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.

    0 讨论(0)
  • 2020-12-04 15:29

    This use as well as:

      CreateMap<Azmoon, AzmoonViewModel>()
                .ForMember(d => d.CreatorUserName, m => m.MapFrom(s => 
     s.CreatedBy.UserName))
                .ForMember(d => d.LastModifierUserName, m => m.MapFrom(s => 
    s.ModifiedBy.UserName)).IgnoreAllNonExisting();
    
    0 讨论(0)
  • 2020-12-04 15:30

    a sample implementation would be as follows:

    Mapper.CreateMap<Game, GameViewModel>()
      .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<Game, GameViewModel>()
        .ForMember(dest => dest.Prize, opt => opt.Ignore());
    
    0 讨论(0)
  • 2020-12-04 15:36

    Are you doing it like this

    Mapper.CreateMap<SourceType,DestinationType>().ForMember(What ever mapping in here)
    

    This page has some good examples

    0 讨论(0)
  • 2020-12-04 15:49

    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.

    0 讨论(0)
提交回复
热议问题