【发布时间】: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