c# - AutoMapper:调用Map()函数时忽略一些参数

标签 c# automapper

我想在调用 Map 函数时忽略一些映射。

这是我创建 map 的地方:

Mapper.CreateMap<User, UserViewModel>()
    .ForMember(dest => dest.WebLicenseCount, opt => opt.MapFrom(src => GetCount(src, "0801")))
    .ForMember(dest => dest.MobileLicenseCount, opt => opt.MapFrom(src => GetCount(src, "0901")))
    .ForMember(dest => dest.ExcelAddInLicenseCount, opt => opt.MapFrom(src => GetCount(src, "0895")))
    .ForMember(dest => dest.NextExpirationDate, opt => opt.MapFrom(src => src.Licences.Min(l => l.LicenceProducts.Min(lp => lp.ExpirationDate))))
    .ForMember(dest => dest.Licences, opt => opt.MapFrom(src => src.Licences.ToList()))
    .ForMember(dest => dest.TicketsCount, opt => opt.MapFrom(src => src.Tickets.Count(t => t.Status != (int)TicketStatusType.Closed)))
    .ForMember(dest => dest.ParentContact, opt => opt.MapFrom(src => src.Contact))
    .ForMember(dest => dest.ParentUser, opt => opt.MapFrom(src => src.User2))
    .ForMember(dest => dest.Contacts, opt => opt.MapFrom(src => src.Contacts))
    .ForMember(dest => dest.MainContact, opt => opt.Ignore())
    .ForMember(dest => dest.SessionID, opt => opt.Ignore())
    ;

在我的 Controller 中我这样做:

users = Mapper.Map<UserViewModel[]>(response.users);

我想在此调用中忽略这些属性的映射:WebLicenseCountMobileLicenseCountExcelAddInLicenseCount

有办法做到这一点吗?

最佳答案

如果这是你只想做一次的事情,那么在 Map() 函数之后用相应的 response.users 覆盖 users 中提到的属性。如果这是您想要经常做的事情,那么这意味着您需要更改映射或为这些情况创建第二种类型(例如 SpecialUser)并为此类型定义不同的映射集。

关于c# - AutoMapper:调用Map()函数时忽略一些参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19690105/

相关文章:

C#调用oracle存储函数

c# - 如何使用 EF Core 3.0 使多个包含更高效

c# - 将项目添加到新集合而不是替换整个集合

c# - 迁移到 AutoMapper 4.2/5.0 时,我应该在依赖注入(inject)容器中存储 IMapper 实例还是 MapperConfiguration 实例?

c# - 自动映射器首先映射 EF 可投影属性,然后映射其他属性

c# - 在 IGrouping 中获取 "Value"属性

c# - 使用 C# Thread 删除文件

c# - 播种多对多 EF Code First 关系

c# - 使用存储库的对象映射器

c# - 如何使用 Entity Framework 使用 DTO 更新数据库中的实体