ASP.net在发布新条目时evrything很好但是在事后调用时,数据消失了

问题描述 投票:0回答:1

我有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();
    }

当我创造一个新游戏时,evrything似乎很好。它用新的GameId回复了我的游戏,并且似乎添加了Loctions / Clues / Suspects。但是当我稍后尝试调用它们时,列表似乎是空的。我在创作或打电话时做错了吗?或者是我的关系完全搞砸了我想要实现的目标,这是一个从我的数据库中随机位置/嫌疑人/线索的游戏。

asp.net asp.net-mvc database
1个回答
0
投票

使用:_dbcontext.Games.Include(g => g.GameLocations).Include(g => g.GameSuspects).Include(g => g.GameClues).ToList()包含相关项目。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.