public static GameDTO CreateNewGame(GameDTO game, out string errorMessage) { using (var dbContext = new FilmQuizDBEntities()) { try { // Setting game fields var newGame = new Games() { Name = game.Name, PlayerTurn = 1, TurnNumber = 1, Turns = game.Turns, }; // Check if category is all or specific if (game.Category == null) { newGame.Category = null; } else { newGame.Category = game.Category.Id; } // Creates game in db dbContext.Games.Add(newGame); dbContext.SaveChanges(); // Add players string em = ""; AddPlayersToGame(game.Players, newGame.G_Id, out em); if (!string.IsNullOrEmpty(em)) { errorMessage = em; return null; } else { // Add questions AddQuestionsToGame(newGame.G_Id, out em, newGame.Category); if (!string.IsNullOrEmpty(em)) { errorMessage = em; return null; } else { // Returns a fresh copy from the db, of the newly created game var getGame = GetGame(newGame.G_Id, out em); if (!string.IsNullOrEmpty(em)) { errorMessage = em; return null; } else { errorMessage = null; return getGame; } } } } catch(Exception e) { errorMessage = "Something went wrong on the server: " + e.Message; return null; } } }
private static GameDTO ModelGameToDTO(Games game) { var gameResult = new GameDTO { Id = game.G_Id, Name = game.Name, PlayerTurn = game.PlayerTurn, TurnNumber = game.TurnNumber, Turns = game.Turns }; var players = new List<PlayerDTO>(); foreach (var p in game.Players) { players.Add(ModelPlayerToDTO(p)); } var questions = new List<QuestionDTO>(); foreach (var q in game.Questions) { questions.Add(ModelQuestionToDTO(q)); } gameResult.Players = players; gameResult.Questions = questions; if (game.Categories == null) { gameResult.Category = null; } else { gameResult.Category = ModelCategoryToDTO(game.Categories); } return gameResult; }