如何直接显示子类别CategoryName而非父类别Category?
解决ProductModel中CategoryName显示错误的问题
问题原因
调试时能在Product实体的Category属性中找到正确的CategoryName,但返回的ProductModel里的CategoryName显示为Data.Entities.Product(实际应为ProductCategory类型的ToString结果),说明查询或映射过程中未将Category实体的CategoryName字符串赋值给ProductModel的对应字段,反而错误赋值了Category实体对象本身。
解决方案
1. 修正Repository查询逻辑(手动投影)
如果GetAllWithDetailsAsync方法是直接返回模型而非通过映射工具,需在查询时显式关联Category并完成字段赋值:
// 在ProductRepository的GetAllWithDetailsAsync方法中 public async Task<List<ProductModel>> GetAllWithDetailsAsync() { return await _context.Products .Include(p => p.Category) // 必须加载Category关联数据 .Select(p => new ProductModel { Id = p.Id, ProductCategoryId = p.ProductCategoryId, CategoryName = p.Category.CategoryName, // 关键:将Category的Name赋值给模型字段 ProductName = p.ProductName, Price = p.Price, ReceiptDetailIds = p.ReceiptDetails.Select(rd => rd.Id).ToList() }) .ToListAsync(); }
2. 配置AutoMapper映射规则(使用映射工具时)
若用AutoMapper实现实体到模型的转换,需在映射Profile中明确指定CategoryName的取值来源:
public class ProductMappingProfile : Profile { public ProductMappingProfile() { CreateMap<Product, ProductModel>() // 指定CategoryName从Product.Category.CategoryName获取 .ForMember(dest => dest.CategoryName, opt => opt.MapFrom(src => src.Category.CategoryName)); } }
同时确保查询时已加载Category关联,避免懒加载导致的空引用:
// 在Repository方法中 public async Task<List<Product>> GetAllWithDetailsAsync() { return await _context.Products .Include(p => p.Category) .Include(p => p.ReceiptDetails) .ToListAsync(); }
3. 排查错误赋值场景
检查是否有代码误将Category实体对象赋值给ProductModel.CategoryName字段(比如误写为model.CategoryName = product.Category),这种情况会导致ToString()输出实体类型名,需修正为model.CategoryName = product.Category.CategoryName。
内容的提问来源于stack exchange,提问作者Oana
相关产品推荐
相关产品推荐

