AutoMapper 配置忽略,配置对象可以为空。AutoMapper对象如果不为空则映射。解决AutoMapper自动创建对象。AutoMapper自动new ef的导航属性对象。AutoMapper中写为空判断 电脑版发表于:2022/5/23 17:19 [TOC] ### AutoMapper 配置忽略 ``` //忽略属性 CreateMap<EmployeeArchivesDto, EmployeeArchives>() .ForMember(dest => dest.UserInfo, opt => opt.Ignore()) .ForMember(dest => dest.ArchivesType, opt => opt.Ignore()); ``` ### AutoMapper 配置对象可以为空 ``` CreateMap<EmployeeArchivesDto, EmployeeArchives>() .ForMember(dest => dest.UserInfo, opt => opt.AllowNull()) .ForMember(dest => dest.ArchivesType, opt => opt.AllowNull()); ``` ### 如果字段名字不一样,可以这样配置映射关系 ``` CreateMap<JToken, SchedulHeadViewModel>() .ForMember(dest => dest.HospitalId, options => options.MapFrom(c => c.SelectToken("Hospital_ID"))) .ForMember(dest => dest.BranchId, options => options.MapFrom(c => c.SelectToken("Branch_ID"))) .ForMember(dest => dest.SchedulId, options => options.MapFrom(c => c.SelectToken("ScheduHeadID"))); ``` ### 如果想要取子对象数据的映射可以这样配置 ``` CreateMap<EmployeeArchives, EmployeeArchivesDto>() .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.UserInfo.UserName)) .ForMember(dest => dest.ArchivesTypeName, opt => opt.MapFrom(src => src.ArchivesType.archives_type_name)) .ReverseMap(); ``` 但是这里要注意的,就是这里使用了ReverseMap,是双向映射,这里边使用了导航属性的赋值,src.ArchivesType.xxx和src.UserInfo.xx,这种虽然查询的时候没有问题,但是如果是添加的时候,也就是从EmployeeArchivesDto映射到EmployeeArchives的时候会`自动new对象`就会有问题,就会自动去添加外键了。 #### 解决方法就是两个映射单独配置,就不会相互影响了,复杂情况下双向很容易出错 dto到ef实体的映射也就是EmployeeArchivesDto到EmployeeArchives的映射就直接配置一个简单的映射就行,不会设置到子对象的赋值 ``` CreateMap<EmployeeArchivesDto, EmployeeArchives>(); ``` 然后ef实体到dto的映射,就涉及到子对象的取值赋值了,注意这里就不需要调用`ReverseMap()`了 ``` CreateMap<EmployeeArchives, EmployeeArchivesDto>() .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.UserInfo.UserName)) .ForMember(dest => dest.ArchivesTypeName, opt => opt.MapFrom(src => src.ArchivesType.archives_type_name)); ``` #### 还有一种解决方法就是写成双向,然后加一点判断 ``` CreateMap<EmployeeArchivesDto, EmployeeArchives>(); CreateMap<EmployeeArchives, EmployeeArchivesDto>() .AfterMap((src, dst) => { if (src.UserInfo != null) { dst.UserName = src.UserInfo.UserName; } if (src.ArchivesType != null) { dst.ArchivesTypeName = src.ArchivesType.archives_type_name; } }); ``` 两种方法大家都可以根据不同情况去尝试一下!