我有两个类:游戏和定位。我的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; }
}
Location类:
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的游戏,并且位置/线索/疑点似乎被添加了。但是当我稍后尝试调用它们时,列表似乎是空的。我在创建或调用时做了什么完全错误的事情吗?或者是我的关系完全搞乱了我想要实现的目标,那就是从我的数据库中制作一个具有随机位置/嫌疑人/线索的游戏。
发布于 2018-12-06 05:41:52
使用:_dbcontext.Games.Include(g => g.GameLocations).Include(g => g.GameSuspects).Include(g => g.GameClues).ToList()
包含相关项。
https://stackoverflow.com/questions/53633919
复制相似问题