【问题标题】:One API call to retrieve all items in the model一个 API 调用来检索模型中的所有项目
【发布时间】:2019-11-25 10:26:29
【问题描述】:

我使用 Net Core 2.2 创建了一个简单的 web 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 调用吗?

谢谢!

【问题讨论】:

  • 不确定我是否理解这个问题。如果您想在结果中包含 MonterList,那么只需Include 即可。
  • @IvanStoev 我错误地认为在 DungeonList 的类模型中包含 MonsterList 意味着它也会被填充。就像每个具有相同 DungeonId 的怪物都会被包括在内
  • 嗯,这是 EF Core 的一个常见错误 - 如果没有特别要求这样做,它包含(加载)相关数据。阅读Loading Related Data 文档主题是必须的:)

标签: entity-framework-core asp.net-core-2.0


【解决方案1】:

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

[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]

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2011-09-02
    • 2011-11-21
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多