ASP.NET Boilerplate中使用AsyncCrudAppService获取关联实体数据填充DTO
问题原因
你的AutoMapper配置逻辑本身没有错误,返回CategoryDescription为null的核心原因是:EF Core默认不会自动加载关联的导航属性,ABP框架自带的AsyncCrudAppService默认的查询逻辑也没有包含关联实体的预加载,最终查询得到的Item实体的Category属性为null,AutoMapper自然无法映射到对应的Description值。
解决方法
方案1:重写应用服务的查询方法,手动添加预加载(最推荐)
直接在你的ItemAppService中重写AsyncCrudAppService提供的查询相关方法,通过Include指定预加载关联的Category属性即可:
public class ItemAppService : AsyncCrudAppService<Core.Item, ItemDto>, IItemAppService { public ItemAppService(IRepository<Core.Item, int> repository) : base(repository) { } // 重写GetAll分页查询的过滤逻辑,添加关联实体预加载 protected override IQueryable<Core.Item> CreateFilteredQueryAsync(PagedAndSortedResultRequestDto input) { return base.CreateFilteredQueryAsync(input) .Include(i => i.Category); } // 重写单条Get查询的逻辑,添加关联实体预加载 protected override Task<Core.Item> GetEntityByIdAsync(int id) { return Repository.GetAll() .Include(i => i.Category) .FirstOrDefaultAsync(i => i.Id == id); } }
方案2:优化AutoMapper配置,避免空引用异常
建议同时调整AutoMapper的映射规则,添加空值保护,避免当Item没有绑定分类(CategoryId为null)时触发空引用异常:
public class ItemProfile : Profile { public ItemProfile() { CreateMap<ItemDto, Core.Item>(); CreateMap<Core.Item, ItemDto>() // 使用空传播运算符,Category为null时直接返回null .ForMember(p => p.CategoryDescription, options => options.MapFrom(x => x.Category?.Description)); } }
可选方案:开启EF Core懒加载(不推荐)
如果项目已经开启了EF Core的懒加载代理功能,无需手动写Include也能自动加载关联属性,但该方案容易出现N+1查询的性能问题,生产环境更推荐使用预加载方案。
内容的提问来源于stack exchange,提问作者ivanph
相关产品推荐
相关产品推荐

