private static void AddQuestionsToGame(int gameId, out string errorMessage, int? categoryId = null) { using (var dbContext = new FilmQuizDBEntities()) { try { var game = dbContext.Games .Where(g => g.G_Id == gameId) .SingleOrDefault(); List<Questions> questions; if (categoryId != null) { questions = dbContext.Questions .Where(q => q.Category == categoryId) .ToList(); } else { questions = dbContext.Questions.ToList(); } game.Questions = questions; dbContext.SaveChanges(); errorMessage = null; } catch (Exception e) { errorMessage = "Something went wrong on the server: " + e.Message; } } }
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 void AddPlayersToGame(List<PlayerDTO> players, int gameId, out string errorMessage) { using (var dbContext = new FilmQuizDBEntities()) { try { foreach (var p in players) { var newPlayer = new Players { Name = p.Name, Game = gameId, Number = p.Number, Points = 0, }; dbContext.Players.Add(newPlayer); } dbContext.SaveChanges(); errorMessage = null; } catch(Exception e) { errorMessage = "Something went wrong on the server: " + e.Message; } } }