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

调用Get All接口返回外键关联UnitSize数据的问题求助

问题排查与解决建议

1. 关联数据未加载

EF Core默认不会自动加载导航属性的关联数据,你当前查询UnitOfMeasure时没有显式加载关联的UnitOfMeasureSize,导致返回的UnitSize字段为空。
修改GetAllAsync方法,添加Include加载关联数据,同时修正OrderBy未生效的问题(LINQ的OrderBy会返回新序列,需要重新赋值):

public async Task<IEnumerable<UnitOfMeasureViewModel>> GetAllAsync()
{
    var result = await _unitOfMeasureRepo.FindByAsync(uom => uom.TenantId == TenantId);
    // 显式加载关联的UnitSize,若仓储不支持Include可直接用DbContext查询
    result = result.Include(uom => uom.UnitSize).OrderBy(r => r.Name);
    
    return _mapper.Map<List<UnitOfMeasure>, List<UnitOfMeasureViewModel>>(result.ToList());
}

如果用DbContext直接查询写法如下:

var result = await _context.UnitOfMeasures
    .Where(uom => uom.TenantId == TenantId)
    .Include(uom => uom.UnitSize)
    .OrderBy(r => r.Name)
    .ToListAsync();

2. 主键配置错误

UnitOfMeasureSize实体的主键列名配置有误,当前[Column("UnitOfMeasureSize")]指定的列名和表名重复,需要核对数据库实际主键字段名修改配置:

[Key]
// 替换为你数据库中UnitOfMeasureSize表的实际主键列名,通常为UnitOfMeasureSizeId
[Column("UnitOfMeasureSizeId")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }

3. 接口实现检查

你前端调用的/${unitOfMeasureId}/UnitSize接口,请确认后端是否有对应实现,示例实现如下:

[HttpGet("{unitOfMeasureId}/UnitSize")]
public async Task<IActionResult> GetUnitSizes(string unitOfMeasureId)
{
    var sizes = await _context.UnitOfMeasureSizes
        .Where(s => s.UnitOfMeasureId == unitOfMeasureId && s.TenantId == TenantId)
        .ToListAsync();
    return Ok(sizes);
}

如果你选择在GetAllAsync接口一次性返回所有UOM和关联的Size,前端不需要单独调用getUnitSizes接口,直接从GetAll返回结果中取每个UOM的UnitSize字段渲染即可。

4. 映射与序列化排查

  • 检查AutoMapper配置是否包含UnitOfMeasure到UnitOfMeasureViewModel的UnitSize字段映射,避免映射时该字段被忽略
  • 若直接返回实体而非ViewModel,注意两个实体存在循环引用,会导致JSON序列化失败,可在Program.cs添加如下配置:
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
    });

内容的提问来源于stack exchange,提问作者Matthew Lemke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:45:06