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

如何在API响应中正确返回子列表?Steps字段为null问题排查

问题:食谱API中Steps字段返回null而非步骤列表

我开发了一个食谱API,Recipe模型包含Steps属性(Step类型的列表),但API返回结果中Steps字段为null,而非预期的步骤列表。种子数据里已经添加了Steps数据,不确定是不是API控制器代码的问题。

实体类代码

Recipe类

namespace API.Models
{
    public class Recipe
    {
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Author { get; set; }
        public int PrepTime { get; set; }
        public DateTime DateCreate { get; set; } = DateTime.UtcNow;
        public string Diet { get; set; }
        [Required]
        public int Servings { get; set; }
        public int UserId { get; set; }
        [Required]
        public string PhotoURL { get; set; }
        [Required]  
        public List<Step> Steps { get; set; }
        public string Cuisine { get; set; }
        public string DishType { get; set; }
        [Required]
        public string Ingredients { get; set; }
        public List<Rating> Ratings { get; set; }
    }
}

Step类

namespace API.Models
{
    public class Step
    {
        public int Id { get; set; }
        public string Details{ get; set; }
        public int RecipeId { get; set; }
    }
}

API控制器GetRecipes端点代码

[HttpGet]
public ActionResult<List<Recipe>> GetRecipes()
{
    var recipes = context.Recipes.ToList();
    
    return Ok(recipes);
}

Swagger响应结果

[
  {
    "id": 1,
    "title": "Creamy Chicken and Dumplings",
    "author": "Unknown",
    "prepTime": 30,
    "dateCreate": "2020-04-20T00:00:00",
    "diet": "Non vegetarian",
    "servings": 2,
    "userId": 0,
    "photoURL": "https://i1.wp.com/thecraveablekitchen.com/wp-content/uploads/2017/12/Creamy-Chicken-and-Dumplings-Square-1.jpg?fit=550%2C550&ssl=1",
    "steps": null,
    "cuisine": null,
    "dishType": null,
    "ingredients": "Heavy cream, chicken",
    "ratings": null
  }
]

解决方案

这是Entity Framework默认延迟加载导致的问题——EF不会自动加载导航属性(比如Steps),除非你明确指定要包含关联数据。

方法1:显式加载关联数据(推荐)

修改控制器方法,使用Include方法指定加载Steps:

using Microsoft.EntityFrameworkCore; // 需添加此命名空间

[HttpGet]
public ActionResult<List<Recipe>> GetRecipes()
{
    var recipes = context.Recipes
        .Include(r => r.Steps) // 显式包含Steps关联数据
        .ToList();
    
    return Ok(recipes);
}

方法2:启用全局延迟加载

如果需要所有导航属性自动加载,可在DbContext中配置:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer("你的数据库连接字符串")
        .UseLazyLoadingProxies(); // 启用延迟加载代理
}

同时需将Recipe类的Steps属性改为virtual:

public virtual List<Step> Steps { get; set; }

额外检查

确认种子数据中的Step对象已正确设置RecipeId,确保其对应Recipe的Id值,否则即使加载关联也不会返回有效数据。

内容的提问来源于stack exchange,提问作者Mohamed Ammar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:45:41