You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何直接显示子类别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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:41:05