/** * Create teamPlayers attached to the league */ private async Task <League> createLeagueWithTeamPlayers(League leagueInCreation, int ruleSetId) { List <TeamPlayer> teamPlayersCreated = new List <TeamPlayer>(); // for each team players, we see in database if it already exists, if so, we add it to the leage without creating it before foreach (TeamPlayer tp in leagueInCreation.TeamPlayers) { TeamPlayer dbTeamPlayer = this.db.TeamPlayers.Where(tpWhere => tpWhere.PlayerId == tp.PlayerId && tpWhere.TeamId == tp.TeamId).FirstOrDefault(); if (dbTeamPlayer != null) { teamPlayersCreated.Add(dbTeamPlayer); } else { // Add the team players to the season teamPlayersCreated.Add(tp); } } leagueInCreation.TeamPlayers = teamPlayersCreated; // we update the league then leagueInCreation = this.db.Leagues.Add(leagueInCreation); await db.SaveChangesAsync(); // Then we create the matches and the scores leagueInCreation.Matches = await ruleSetRepo.createMatchAndScore(leagueInCreation.TeamPlayers, ruleSetId); db.Entry(leagueInCreation).State = EntityState.Modified; await db.SaveChangesAsync(); return(leagueInCreation); }