public void InitilizeFirstMatches(Guid tournamentId) { var tournament = tournamentRepository.GetWithInclude(t => t.Players) .FirstOrDefault(t => t.TournamentId == tournamentId); if (tournament == null) { return; } var players = tournament.Players; var finalMatch = Bracket.Create(players); var queue = new Queue <MatchNode>(); queue.Enqueue(finalMatch); while (queue.Count > 0) { var currentMatchNode = queue.Dequeue(); var match = currentMatchNode.Match; match.TournamentId = tournamentId; if (currentMatchNode.NextMatchNode != null) { match.NextMatchId = currentMatchNode.NextMatchNode.Match.MatchId; } currentMatchNode.Match = matchRepository.Create(match); if (currentMatchNode.NextMatchNode != null) { var nextMatchNode = currentMatchNode.NextMatchNode; if (currentMatchNode == nextMatchNode.PrevLeftMatchNode) { nextMatchNode.Match.PrevFirstMatchId = currentMatchNode.Match.MatchId; } else if (currentMatchNode == nextMatchNode.PrevRightMatchNode) { nextMatchNode.Match.PrevSecondMatchId = currentMatchNode.Match.MatchId; } matchRepository.Update(nextMatchNode.Match); } if (currentMatchNode.PrevLeftMatchNode != null) { queue.Enqueue(currentMatchNode.PrevLeftMatchNode); } if (currentMatchNode.PrevRightMatchNode != null) { queue.Enqueue(currentMatchNode.PrevRightMatchNode); } } }