使用与使用HttpPost添加新条目相同的方法更新现有表行



我有一个使用.NetCore实体框架的网络游戏。

我有一个方法,它使用HttpPost在数据库中创建一个新的Monster。

该方法还需要向名为DungeonList的表中的现有Dungeon添加一个外键,即新的MonsterId。

我得到了该方法正确创建新怪物的部分。

然而,我不知道如何将新的怪物ID插入地下城列表的适当地下城。

我不太清楚如何获得地牢的身份证。

我应该从前端进入地下城ID吗?

我真的很困惑。

这是我到目前为止所拥有的,但我不确定接下来该何去何从。

我想要一些建议。。。非常感谢。

[HttpPost]
public async Task<ActionResult<MonsterList>> PostMonsterList(MonsterList monsterList)
{
monsterList.MonsterId = Guid.NewGuid();
_context.MonsterList.Add(monsterList);
var dungeonListRef = new DungeonList();
if(dungeonListRef.MonsterId == null)
{
// ????
}

try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (MonsterListExists(monsterList.MonsterId))
{
return Conflict();
}
else
{
throw;
}
}
_context.DungeonList.Add(dungeonListRef);
return CreatedAtAction("GetMonsterList", new { id = monsterList.MonsterId }, monsterList);
}

在您的"添加新怪物"页将下拉列表的地下城ID发送到PostMonsterList功能。

[HttpPost]
public async Task<ActionResult<MonsterList>> PostMonsterList(Guid dungeonId, MonsterList monsterList)
{
Guid newMonsterId = Guid.NewGuid();
monsterList.MonsterId = newMonsterId;
_context.MonsterList.Add(monsterList);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (MonsterListExists(monsterList.MonsterId))
{
return Conflict();
}
else
{
throw;
}
}
var dungeonList = _context.DungeonList.Where(x => x.DungeonId == dungeonId).FirstOrDefault();
dungeonList.MonsterId = newMonsterId;
_context.DungeonList.Update(dungeonList);
await _context.SaveChangesAsync();
return CreatedAtAction("GetMonsterList", new { id = monsterList.MonsterId }, monsterList);
}

最新更新