IQueryable转换为DTO列表时返回传入参数而非查询数据的原因
问题:AutoMapper映射未返回查询数据,反而返回方法参数内容
原因分析
- AutoMapper映射规则缺失:
CollectionsSectionRolesFlatDTO包含嵌套的CollectionsDTO和SectionRoleDto对象,但目标CollectionsSectionRolesDTO是平铺属性结构,两者属性层级不匹配。当前AutoMapper配置仅创建了基础映射关系,未定义嵌套属性到平级属性的映射规则,导致AutoMapper无法正确赋值,最终返回的DTO属性保留默认值(或被误判为方法参数内容)。 - LINQ查询未赋值Id属性:构造
CollectionsSectionRolesFlatDTO的Collections对象时,未给Id属性赋值,导致目标DTO的Id始终为空。
解决方法
方法1:完善AutoMapper映射配置
明确指定嵌套属性到目标平级属性的映射规则,修改AutoMapper配置:
CreateMap<Collections, CollectionsDTO>(); CreateMap<CollectionsSectionRolesFlatDTO, CollectionsSectionRolesDTO>() // 映射Collections对象的属性到目标DTO对应字段 .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Collections.Id)) .ForMember(dest => dest.CollectionTitleEn, opt => opt.MapFrom(src => src.Collections.CollectionTitleEn)) .ForMember(dest => dest.CollectionTitleAr, opt => opt.MapFrom(src => src.Collections.CollectionTitleAr)) .ForMember(dest => dest.CoverImagePath, opt => opt.MapFrom(src => src.Collections.CoverImagePath)) .ForMember(dest => dest.SectionRoleId, opt => opt.MapFrom(src => src.Collections.SectionRoleId)) // 映射SectionRole对象的属性到目标DTO对应字段 .ForMember(dest => dest.NameAr, opt => opt.MapFrom(src => src.SectionRole.NameAr)) .ForMember(dest => dest.NameEn, opt => opt.MapFrom(src => src.SectionRole.NameEn));
同时修改LINQ查询,补充CollectionsDTO的Id赋值:
select new CollectionsSectionRolesFlatDTO { Collections = new CollectionsDTO { Id = c.Id, // 新增Id赋值 CollectionTitleAr = c.CollectionTitleAr, CollectionTitleEn = c.CollectionTitleEn, CoverImagePath = c.CoverImagePath, SectionRoleId = c.SectionRoleId, }, SectionRole = new SectionRoleDto { NameAr = sr.NameAr, NameEn = sr.NameEn } }
方法2:直接构造目标DTO(更高效)
跳过中间的CollectionsSectionRolesFlatDTO,在LINQ查询中直接生成CollectionsSectionRolesDTO,避免AutoMapper映射问题:
var collectionsDto = (from c in db.Collections join sr in db.SectionRole on c.SectionRoleId equals sr.Id select new CollectionsSectionRolesDTO { Id = c.Id, CollectionTitleAr = c.CollectionTitleAr, CollectionTitleEn = c.CollectionTitleEn, CoverImagePath = c.CoverImagePath, SectionRoleId = c.SectionRoleId, NameAr = sr.NameAr, NameEn = sr.NameEn }) .ToList(); return Ok(collectionsDto);
该方法无需额外AutoMapper配置,直接从数据库查询生成目标DTO,性能更优且规避映射错误。
内容的提问来源于stack exchange,提问作者testy
相关产品推荐
相关产品推荐

