private static void AddTeamToLeague(FootballEntities context, Team team, League league) { if (league != null) { if (team.Leagues.Contains(league)) { Console.WriteLine("Existing team in league: {0} belongs to {1}", team.TeamName, league.LeagueName); } else { team.Leagues.Add(league); context.SaveChanges(); Console.WriteLine("Added team to league: {0} to league {1}", team.TeamName, league.LeagueName); } } }
private static void CreateNewTeamsIfNotExists(FootballEntities context, League league, IEnumerable<XElement> xTeams) { foreach (var xTeam in xTeams) { var teamName = xTeam.Attribute("name").Value; var xCountry = xTeam.Attribute("country"); string countryName = null; if (xCountry != null) { countryName = xCountry.Value; } var team = context.Teams .Include(t => t.Leagues) .FirstOrDefault(t => t.TeamName == teamName && t.Country.CountryName == countryName); if (team != null) { Console.WriteLine("Existing team: {0} ({1})", team.TeamName, countryName ?? "no country"); } else { team = new Team() { TeamName = teamName, Country = context.Countries.FirstOrDefault(c => c.CountryName == countryName) }; context.Teams.Add(team); context.SaveChanges(); Console.WriteLine("Created team: {0} ({1})", team.TeamName, countryName ?? "no country"); } AddTeamToLeague(context, team, league); } }