首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >发布新条目时的ASP.net一切都很好,但在之后调用时,数据就消失了

发布新条目时的ASP.net一切都很好,但在之后调用时,数据就消失了
EN

Stack Overflow用户
提问于 2018-12-05 21:52:14
回答 1查看 34关注 0票数 0

我有两个类:游戏和定位。我的API的目的是,我可以创建一个新的游戏,并在该游戏中,从数据库中添加2个随机位置。

游戏类:

代码语言:javascript
复制
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类:

代码语言:javascript
复制
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; }
}

这就是我尝试创建一个新游戏并添加位置的方法:

代码语言:javascript
复制
    [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);
    }

这是我尝试调用所有已创建游戏的列表的方法:

代码语言:javascript
复制
    [HttpGet("getGames")]
    public ActionResult<List<Game>> GetGames()
    {
        return _dbcontext.Games.ToList();
    }

当我创建一个新游戏时,一切似乎都很好。它给我返回了一个带有新GameId的游戏,并且位置/线索/疑点似乎被添加了。但是当我稍后尝试调用它们时,列表似乎是空的。我在创建或调用时做了什么完全错误的事情吗?或者是我的关系完全搞乱了我想要实现的目标,那就是从我的数据库中制作一个具有随机位置/嫌疑人/线索的游戏。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53633919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档