一次 API 调用以检索模型中的所有项目

One API call to retrieve all items in the model

我使用 Net Core 2.2 创建了一个简单的网站 api。我下面有这个 api 控制器,它可以获取一个特定的地牢。

它返回一个地牢作为 JSON,但它没有返回与该地牢关联的 MonsterList。

这是我的控制器:

    // GET: api/DungeonLists/5
    [HttpGet("{id}")]
    public async Task<ActionResult<DungeonList>> GetDungeonList(Guid id)
    {
        var dungeonList = await _context.DungeonList.FindAsync(id);

        if (dungeonList == null)
        {
            return NotFound();
        }

        return dungeonList;
    }

这是我的地牢模型。如您所见,它有一个 MonsterList。

    public partial class DungeonList
{
    public DungeonList()
    {
        MonsterList = new HashSet<MonsterList>();
    }

    public Guid DungeonId { get; set; }
    public string DungeonName { get; set; }
    public string DungeonDesc { get; set; }
    public string MapArea { get; set; }
    public bool ShowProgress { get; set; }
    public bool? DungeonResumable { get; set; }

    public virtual ICollection<MonsterList> MonsterList { get; set; }
}

这是我的 MonsterList 模型:

    public partial class MonsterList
{
    public string MonsterId { get; set; }
    public Guid DungeonId { get; set; }
    public string MonsterName { get; set; }
    public byte? MonsterType { get; set; }
    public bool IsBossMonster { get; set; }

    public virtual DungeonList Dungeon { get; set; }
}

我希望 JSON 也显示与地牢相关的怪物列表。

有办法吗?或者我需要进行单独的 API 调用吗?

谢谢!

您需要将代码更改为以下内容:

[HttpGet("{id}")]
public async Task<ActionResult<DungeonList>> GetDungeonList(Guid id)
{
    var dungeonList = await _context.DungeonList
                                    .Include(i => i.MonsterList)
                                    .FirstOrDefaultAsync(p => p.Id = id);

    if (dungeonList == null)
    {
        return NotFound();
    }

    return dungeonList;
}

此外,由于您没有使用 LazyLoading,因此不需要 MonsterList 集合上的 [virtual]