public bool DeletePlayer(string playerName) { bool DeleteGood = false; using (var db = new PlayerDbContext()) { foreach (PlayerDb checkDb in db.PlayersDb) { // Search through DB for player if (checkDb.PlayerName == playerName) { // If there are scores, remove them first if (checkDb.NumScores > 0) { using (var db1 = new PlayerDbContext()) { foreach (PlayerScore remScore in db1.PlayerScores) { if (checkDb.PlayerDbID == remScore.PlayerDbID) { db1.PlayerScores.Remove(remScore); } } db1.SaveChanges(); db1.Dispose(); } } db.PlayersDb.Remove(checkDb); } } db.SaveChanges(); db.Dispose(); DeleteGood = true; } return DeleteGood; }
public bool SavePlayerToDb(Player player) { bool SaveGood = false, NewPlayer = true; PlayerDb AddPlayer = null; int HoldPlayerDbID = 0; try { // If a player exisits in db, find and attach to a context to update // Get a context to the DB and save the passed object using (var db = new PlayerDbContext()) { foreach (PlayerDb findPlayer in db.PlayersDb) { if (findPlayer.PlayerName == player.PlayerName) { NewPlayer = false; // Copy values to object HoldPlayerDbID = findPlayer.PlayerDbID; findPlayer.PlayerName = player.PlayerName; findPlayer.GameStatus = player.GameStatus; findPlayer.NumScores = player.NumberOfScores; } } // If new player, add to DB if (NewPlayer) { AddPlayer = new PlayerDb(); AddPlayer.PlayerName = player.PlayerName; AddPlayer.GameStatus = player.GameStatus; AddPlayer.NumScores = player.NumberOfScores; db.PlayersDb.Add(AddPlayer); db.SaveChanges(); HoldPlayerDbID = AddPlayer.PlayerDbID; } // Close DB db.Dispose(); } // If there are scores, update PlayerScores object // Get a context to the DB and save the passed object using (var db = new PlayerDbContext()) { if (player.NumberOfScores > 0) { // Remove Scores first to compensate for score // auto-sorting in domain object // otherwise database would have to be sorted and a // comparison done to insert new scores // this is simpiler :-) foreach (PlayerScore checkScore in db.PlayerScores) { if (checkScore.PlayerDbID == HoldPlayerDbID) db.PlayerScores.Remove(checkScore); } PlayerScore SaveScores = new PlayerScore(); for (int i = 0; i < player.NumberOfScores; i++) { SaveScores.PlayerDbID = HoldPlayerDbID; SaveScores.Score = player.ScoreList[i]; db.PlayerScores.Add(SaveScores); // Start next entry SaveScores = new PlayerScore(); } } db.SaveChanges(); db.Dispose(); // No errors, set return value SaveGood = true; } } catch (Exception e) { Console.WriteLine("DB store exception" + e.Message); SaveGood = false; } return SaveGood; }