ASP.net 发布新条目时一切正常,但之后调用时,数据消失了

牧师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();
    }

当我创建一个新游戏时,一切似乎都很好。它用新的 GameId 重新调整了我的游戏,并且似乎添加了 Loctions/Clues/Suspects。但是当我稍后尝试调用它们时,列表似乎是空的。我的创作或召唤是否完全错误?或者是我的关系完全被我想要实现的目标搞砸了,这就是制作一个具有随机位置/嫌疑人/来自我的数据库的线索的游戏。

果酱

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章