У меня есть 2 класса: игра и местоположение.Цель моего API заключается в том, что я могу создать новую игру, и в этой игре добавляются 2 случайные локации из базы данных.
Класс игры:
public class Game
{
public Game()
{
GameLocations = new List<Location>();
GameSuspects = new List<Suspect>();
GameClues = new List<Clue>();
}
[Key]
public int GameId { get; set; }
public bool GameWon { get; set; }
public ICollection<Location> GameLocations { get; set; }
public ICollection<Suspect> GameSuspects { get; set; }
public ICollection<Clue> GameClues { get; set; }
}
Класс локации:
public class Location
{
public double LocLat { get; set; }
public double LocLong { get; set; }
public string LocDescription { get; set; }
public string LocName { get; set; }
//public ICollection<GameLocation> GameLocations { get; set; }
[Key]
public int LocId { get; set; }
}
Вот как я пытаюсь создать новую игру и добавить к ней локации:
[HttpPost("newgame")]
public IActionResult CreateNewGame()
{
var newGame = new Game();
// add random locations
var location1 = _dbcontext.Locations.Find(1);
var location2 = _dbcontext.Locations.Find(3);
newGame.GameLocations.Add(location1);
newGame.GameLocations.Add(location2);
//add suspects
var suspect1 = _dbcontext.Suspects.Find(1);
var suspect2 = _dbcontext.Suspects.Find(2);
newGame.GameSuspects.Add(suspect1);
newGame.GameSuspects.Add(suspect2);
//add Clues
var clue1 = _dbcontext.Clues.Find(1);
var clue2 = _dbcontext.Clues.Find(2);
newGame.GameClues.Add(clue1);
newGame.GameClues.Add(clue2);
_dbcontext.Games.Add(newGame);
_dbcontext.SaveChanges();
return Created("", newGame);
}
и вот как я пытаюсь вызвать список всех созданных игр:
[HttpGet("getGames")]
public ActionResult<List<Game>> GetGames()
{
return _dbcontext.Games.ToList();
}
Когда я создаю новую игру, все выглядит хорошо.Это возвращает мне игру с новым GameId, и кажется, что добавлены Loctions / Clues / Suspect.Но когда я пытаюсь вызвать их позже, списки оказываются пустыми.Я делаю что-то не так с моим созданием или вызовом?Или мои отношения просто полностью испортили то, чего я пытаюсь достичь, создав игру, в которой есть случайные места / подозреваемые / подсказки из моей базы данных.