如何使用自动映射器?

我试图设置自动映射器转换从实体到 DTO。我知道我应该在 Mapper.CreateMap<Entity, DTO>()之后使用 .ForMember()来设置自定义映射,但是这似乎不是一个可用的方法。

编辑以便澄清: 我并不是在寻找我已经阅读过的文档的链接,也不是在寻找对基本语法的解释。我正在使用正确的语法,正如在答案和文档中描述的那样,例如:

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

如果我在 CreateMap < > 中有一个无效的类型名称,我可以看到“ ForMember”作为一个有效的方法,鼠标移动显示方法签名,正如我通常期望的那样。但是一旦我给它两个有效的类型,ForMember 说它不能解析这个符号,就好像这个方法不可用一样。

在泛型类中是否存在某种我没有遇到的约束?

谢谢

123620 次浏览

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.

Are you doing it like this

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

This page has some good examples

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

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.

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();
 CreateMap<ClassRoom, ClassRoomDto>()
.ForMember(opt => opt.StudentNumber, conf => conf.MapFrom(x => x.Student == null ? (long?)null : x.Student.StudentNumber))
.ForMember(opt => opt.StudentFullName, conf => conf.MapFrom(x => x.Student == null ? null : x.Student.Name + " " + x.Student.Surname))
.ReverseMap()
.ForMember(opt => opt.Student, conf => conf.Ignore());