Esempio n. 1
0
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.GameStatusTypesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.GameStatusTypesFeed.FromJson(rawJson);

            var dbGameStatusTypes = context.GameStatusTypes.ToDictionary(x => x.GameStatusCode);

            foreach (var feedGameStatusType in feed)
            {
                if (!dbGameStatusTypes.TryGetValue(feedGameStatusType.StatusCode, out Model.GameStatusType dbGameStatusType))
                {
                    dbGameStatusType = new Model.GameStatusType
                    {
                        GameStatusCode    = feedGameStatusType.StatusCode,
                        AbstractGameCode  = feedGameStatusType.AbstractGameCode,
                        AbstractGameState = feedGameStatusType.AbstractGameState,
                        CodedGameState    = feedGameStatusType.CodedGameState,
                        DetailedState     = feedGameStatusType.DetailedState,
                        Reason            = feedGameStatusType.Reason
                    };
                    dbGameStatusTypes.Add(dbGameStatusType.GameStatusCode, dbGameStatusType);
                    context.GameStatusTypes.Add(dbGameStatusType);
                }
                else
                {
                    ;                     // TODO: VERIFY NO CHANGES TO PROPERTIES
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.SkyTypesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.SkyTypesFeed.FromJson(rawJson);

            var dbSkyTypes = context.SkyTypes.ToDictionary(x => x.Code);

            foreach (var feedSkyType in feed)
            {
                if (!dbSkyTypes.TryGetValue(feedSkyType.Code, out Model.SkyType dbSkyType))
                {
                    dbSkyType = new Model.SkyType
                    {
                        Code        = feedSkyType.Code,
                        Description = feedSkyType.Description
                    };
                    dbSkyTypes.Add(feedSkyType.Code, dbSkyType);
                    context.SkyTypes.Add(dbSkyType);
                }
                else
                {
                    if (!string.Equals(dbSkyType.Description, feedSkyType.Description, StringComparison.InvariantCultureIgnoreCase))
                    {
                        dbSkyType.Description = feedSkyType.Description;
                    }
                }
            }
            context.SaveChanges();
        }
Esempio n. 3
0
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.VenuesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.VenuesFeed.FromJson(rawJson);

            var dbVenues = context.Venues.ToDictionary(x => x.VenueID);

            foreach (var feedVenue in feed.Venues)
            {
                if (!dbVenues.TryGetValue(feedVenue.Id, out Model.Venue dbVenue))
                {
                    dbVenue = new Model.Venue
                    {
                        VenueID   = feedVenue.Id,
                        VenueName = feedVenue.Name,
                        VenueLink = feedVenue.Link
                    };
                    dbVenues.Add(dbVenue.VenueID, dbVenue);
                    context.Venues.Add(dbVenue);
                }

                if (dbVenue.VenueName != feedVenue.Name)
                {
                    dbVenue.VenueName = feedVenue.Name;
                }
            }
            context.SaveChanges();
        }
Esempio n. 4
0
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.PositionsFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.PositionsFeed.FromJson(rawJson);

            var dbPositions = context.Positions.ToDictionary(x => x.PositionAbbr);

            foreach (var feedPosition in feed)
            {
                if (!dbPositions.TryGetValue(feedPosition.Abbrev, out Model.Position dbPosition))
                {
                    dbPosition = new Model.Position
                    {
                        PositionAbbr = feedPosition.Abbrev,
                        ShortName    = feedPosition.ShortName,
                        FullName     = feedPosition.FullName,
                        FormalName   = feedPosition.FormalName,
                        DisplayName  = feedPosition.DisplayName,
                        PositionCode = feedPosition.Code,
                        IsFielder    = feedPosition.Fielder,
                        IsPitcher    = feedPosition.Pitcher,
                        IsOutfield   = feedPosition.Outfield,
                        PositionType = feedPosition.Type
                    };
                    dbPositions.Add(dbPosition.PositionAbbr, dbPosition);
                    context.Positions.Add(dbPosition);
                }
                else
                {
                    ;                     // TODO: ADD NO-CHANGE VALIDATION LOGIC
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.GameSituationTypesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.GameSituationTypesFeed.FromJson(rawJson);


            var dbGameSituationTypes = context.GameSituationTypes.ToDictionary(x => x.Code);

            foreach (var feedGameSituationType in feed)
            {
                if (!dbGameSituationTypes.TryGetValue(feedGameSituationType.Code, out Model.GameSituationType dbGameSituationType))
                {
                    dbGameSituationType = new Model.GameSituationType
                    {
                        Code         = feedGameSituationType.Code,
                        Description  = feedGameSituationType.Description,
                        IsBatting    = feedGameSituationType.Batting,
                        IsFielding   = feedGameSituationType.Fielding,
                        IsPitching   = feedGameSituationType.Pitching,
                        IsTeam       = feedGameSituationType.Team,
                        NavMenuGroup = feedGameSituationType.NavigationMenu,
                        SortOrder    = feedGameSituationType.SortOrder
                    };
                    dbGameSituationTypes.Add(dbGameSituationType.Code, dbGameSituationType);
                    context.GameSituationTypes.Add(dbGameSituationType);
                }
                else
                {
                    if (dbGameSituationType.Description != feedGameSituationType.Description ||
                        dbGameSituationType.IsBatting != feedGameSituationType.Batting ||
                        dbGameSituationType.IsFielding != feedGameSituationType.Fielding ||
                        dbGameSituationType.IsPitching != feedGameSituationType.Pitching ||
                        dbGameSituationType.IsTeam != feedGameSituationType.Team ||
                        dbGameSituationType.NavMenuGroup != feedGameSituationType.NavigationMenu ||
                        dbGameSituationType.SortOrder != feedGameSituationType.SortOrder)
                    {
                        dbGameSituationType.Code         = feedGameSituationType.Code;
                        dbGameSituationType.Description  = feedGameSituationType.Description;
                        dbGameSituationType.IsBatting    = feedGameSituationType.Batting;
                        dbGameSituationType.IsFielding   = feedGameSituationType.Fielding;
                        dbGameSituationType.IsPitching   = feedGameSituationType.Pitching;
                        dbGameSituationType.IsTeam       = feedGameSituationType.Team;
                        dbGameSituationType.NavMenuGroup = feedGameSituationType.NavigationMenu;
                        dbGameSituationType.SortOrder    = feedGameSituationType.SortOrder;
                    }
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.StatTypesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.StatTypesFeed.FromJson(rawJson);

            var dbStatTypes = context.StatTypes.ToDictionary(x => x.Lookup);

            foreach (var feedStatType in feed)
            {
                if (!dbStatTypes.TryGetValue(feedStatType.LookupParam, out Model.StatType dbStatType))
                {
                    dbStatType = new Model.StatType
                    {
                        Lookup     = feedStatType.LookupParam,
                        Name       = feedStatType.Name,
                        Label      = feedStatType.Label,
                        IsCounting = feedStatType.IsCounting,
                        IsCatching = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "catching", StringComparison.InvariantCultureIgnoreCase)),
                        IsFielding = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "fielding", StringComparison.InvariantCultureIgnoreCase)),
                        IsHitting  = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "hitting", StringComparison.InvariantCultureIgnoreCase)),
                        IsPitching = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "pitching", StringComparison.InvariantCultureIgnoreCase)),
                        IsRunning  = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "running", StringComparison.InvariantCultureIgnoreCase)),
                        IsTeam     = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "team", StringComparison.InvariantCultureIgnoreCase)),
                        IsGame     = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "game", StringComparison.InvariantCultureIgnoreCase)),
                        IsStreak   = feedStatType.StatGroups.Any(x => string.Equals(x.Name, "streak", StringComparison.InvariantCultureIgnoreCase)),
                    };

                    if (feedStatType.StatGroups.Any(x => !dbStatType.IsCatching && !dbStatType.IsFielding && !dbStatType.IsHitting && !dbStatType.IsPitching &&
                                                    !dbStatType.IsRunning && !dbStatType.IsTeam && !dbStatType.IsGame && !dbStatType.IsStreak))
                    {
                        throw new ArgumentException("STATIS A STAT FOR NOTHINGNESS?!");
                    }
                    dbStatTypes.Add(dbStatType.Lookup, dbStatType);
                    context.StatTypes.Add(dbStatType);
                }
                else
                {
                    ;                     // TODO: PUT ADJUSTMENT CODE HERE TO VERIFY NO CHANGES HAVE HAPPENED
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.AssociationsFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.AssociationsFeed.FromJson(rawJson);

            var dbAssociations = context.Associations.ToDictionary(x => x.AssociationID);

            foreach (var feedAssociation in feed.Associations)
            {
                if (!dbAssociations.TryGetValue(feedAssociation.Id, out Model.Association dbAssociation))
                {
                    dbAssociation = new Model.Association
                    {
                        AssociationID   = feedAssociation.Id,
                        AssociationName = feedAssociation.Name,
                        AssociationLink = feedAssociation.Link,
                        AssociationAbbr = feedAssociation.Abbreviation,
                        AssociationCode = feedAssociation.Code,
                        IsEnabled       = !readonlyDisabledAssociationIds.Contains(feedAssociation.Id)
                    };
                    dbAssociations.Add(feedAssociation.Id, dbAssociation);
                    context.Associations.Add(dbAssociation);
                }
                else
                {
                    if (!string.Equals(dbAssociation.AssociationName, feedAssociation.Name))
                    {
                        dbAssociation.AssociationName = feedAssociation.Name;
                    }
                    if (!string.Equals(dbAssociation.AssociationAbbr, feedAssociation.Abbreviation))
                    {
                        dbAssociation.AssociationAbbr = feedAssociation.Abbreviation;
                    }
                    if (!string.Equals(dbAssociation.AssociationCode, feedAssociation.Code))
                    {
                        dbAssociation.AssociationCode = feedAssociation.Code;
                    }
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            var url     = Feeds.JobTypesFeed.GetFeedUrl();
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.JobTypesFeed.FromJson(rawJson);

            feed = feed.OrderBy(x => x.SortOrder.HasValue ? 1 : 2).ThenBy(y => y.SortOrder).ThenBy(z => z.Code).ToList();

            var dbJobTypes = context.JobTypes.ToDictionary(x => x.Code);

            foreach (var feedJobType in feed)
            {
                if (!dbJobTypes.TryGetValue(feedJobType.Code, out Model.JobType dbJobType))
                {
                    dbJobType = new Model.JobType
                    {
                        Code        = feedJobType.Code,
                        Description = feedJobType.Job,
                        SortOrder   = feedJobType.SortOrder
                    };
                    dbJobTypes.Add(feedJobType.Code, dbJobType);
                    context.JobTypes.Add(dbJobType);
                }
                else
                {
                    if (!string.Equals(dbJobType.Description, feedJobType.Job, StringComparison.InvariantCultureIgnoreCase))
                    {
                        dbJobType.Description = feedJobType.Job;
                    }
                    if (dbJobType.SortOrder != feedJobType.SortOrder)
                    {
                        dbJobType.SortOrder = feedJobType.SortOrder;
                    }
                }
            }
            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            Console.WriteLine($"TeamsProcessor - {this.Season}");

            var url     = Feeds.TeamsFeed.GetFeedUrl(this.Season);
            var rawJson = JsonUtility.GetRawJsonFromUrl(url);
            var feed    = Feeds.TeamsFeed.FromJson(rawJson);

            var dbAssociations = context.Associations.ToDictionary(x => x.AssociationID);
            var dbLeagues      = context.Leagues.ToDictionary(x => x.LeagueID);
            var dbDivisions    = context.Divisions.ToDictionary(x => x.DivisionID);
            var dbVenues       = context.Venues.ToDictionary(x => x.VenueID);
            var dbTeams        = context.Teams.ToDictionary(x => x.TeamID);

            var dbVenueSeasons       = context.VenueSeasons.Where(x => x.Season == this.Season).ToDictionary(x => x.VenueID);
            var dbAssociationSeasons = context.AssociationSeasons.Where(x => x.Season == this.Season).ToDictionary(y => y.AssociationID);
            var dbLeagueSeasons      = context.LeagueSeasons.Where(x => x.Season == this.Season).ToDictionary(y => y.LeagueID);
            var dbDivisionSeasons    = context.DivisionSeasons.Where(x => x.Season == this.Season).ToDictionary(y => y.DivisionID);
            var dbTeamSeasons        = context.TeamSeasons.Where(x => x.Season == this.Season).ToDictionary(y => y.TeamID);

            var feedTeams = feed.Teams.OrderBy(x => x.ParentOrgId.HasValue ? 1 : 0).ThenBy(y => y.Sport.Id).ToList();

            foreach (var feedTeam in feedTeams)
            {
                if (!dbAssociations.TryGetValue(feedTeam.Sport.Id.Value, out Model.Association dbAssociation))
                {
                    dbAssociation = new Model.Association
                    {
                        AssociationID   = feedTeam.Sport.Id.Value,
                        AssociationName = feedTeam.Sport.Name,
                        AssociationLink = feedTeam.Sport.Link
                    };
                    dbAssociations.Add(dbAssociation.AssociationID, dbAssociation);
                    context.Associations.Add(dbAssociation);
                }

                Model.League dbLeague = null;
                if (feedTeam.League?.Id != null && !dbLeagues.TryGetValue(feedTeam.League.Id.Value, out dbLeague))
                {
                    dbLeague = new Model.League
                    {
                        LeagueID   = feedTeam.League.Id.Value,
                        LeagueName = feedTeam.League.Name,
                        LeagueLink = feedTeam.League.Link
                    };
                    dbLeagues.Add(dbLeague.LeagueID, dbLeague);
                    context.Leagues.Add(dbLeague);
                }

                Model.Division dbDivision = null;
                if (feedTeam.Division?.Id != null && !dbDivisions.TryGetValue(feedTeam.Division.Id.Value, out dbDivision))
                {
                    dbDivision = new Model.Division
                    {
                        DivisionID   = feedTeam.Division.Id.Value,
                        DivisionName = feedTeam.Division.Name,
                        DivisionLink = feedTeam.Division.Link
                    };
                    dbDivisions.Add(dbDivision.DivisionID, dbDivision);
                    context.Divisions.Add(dbDivision);
                }

                Model.Venue dbVenue = null;
                if (feedTeam.Venue?.Id != null && !dbVenues.TryGetValue(feedTeam.Venue.Id.Value, out dbVenue))
                {
                    dbVenue = new Model.Venue
                    {
                        VenueID   = feedTeam.Venue.Id.Value,
                        VenueName = feedTeam.Venue.Name,
                        VenueLink = feedTeam.Venue.Link
                    };
                    dbVenues.Add(dbVenue.VenueID, dbVenue);
                    context.Venues.Add(dbVenue);
                }

                Model.League dbSpringLeague = null;
                if (feedTeam.SpringLeague?.Id != null && !dbLeagues.TryGetValue(feedTeam.SpringLeague.Id.Value, out dbSpringLeague))
                {
                    dbSpringLeague = new Model.League
                    {
                        LeagueID   = feedTeam.SpringLeague.Id.Value,
                        LeagueName = feedTeam.SpringLeague.Name,
                        LeagueLink = feedTeam.SpringLeague.Link
                    };
                    dbLeagues.Add(dbSpringLeague.LeagueID, dbSpringLeague);
                    context.Leagues.Add(dbSpringLeague);
                }

                Model.Team dbParentOrg = null;
                if (feedTeam.ParentOrgId.HasValue && !dbTeams.TryGetValue(feedTeam.ParentOrgId.Value, out dbParentOrg))
                {
                    dbParentOrg = new Model.Team
                    {
                        TeamID       = feedTeam.ParentOrgId.Value,
                        TeamFullName = feedTeam.ParentOrgName
                    };
                    dbTeams.Add(dbParentOrg.TeamID, dbParentOrg);
                    context.Teams.Add(dbParentOrg);
                }

                if (!dbTeams.TryGetValue(feedTeam.Id, out Model.Team dbTeam))
                {
                    dbTeam = new Model.Team
                    {
                        TeamID       = feedTeam.Id,
                        FileCode     = feedTeam.FileCode,
                        FirstSeason  = feedTeam.FirstYearOfPlay,
                        IsActive     = feedTeam.Active,
                        IsAllStar    = feedTeam.IsAllStarTeam,
                        TeamAbbr     = feedTeam.Abbreviation,
                        TeamCode     = feedTeam.TeamCode,
                        TeamFullName = feedTeam.Name,
                        TeamLocation = feedTeam.LocationName,
                        TeamName     = feedTeam.Name,
                    };
                    dbTeams.Add(dbTeam.TeamID, dbTeam);
                    context.Teams.Add(dbTeam);
                }
                else if (this.IsCurrentSeason)                 // ONLY UPDATE TEAM ENTRY IF IT IS THE CURRENT SEASON
                {
                    if (dbTeam.FileCode != feedTeam.FileCode ||
                        dbTeam.FirstSeason != feedTeam.FirstYearOfPlay ||
                        dbTeam.IsActive != feedTeam.Active ||
                        dbTeam.IsAllStar != feedTeam.IsAllStarTeam ||
                        dbTeam.TeamAbbr != feedTeam.Abbreviation ||
                        dbTeam.TeamCode != feedTeam.TeamCode ||
                        dbTeam.TeamFullName != feedTeam.Name ||
                        dbTeam.TeamLocation != feedTeam.LocationName ||
                        dbTeam.TeamName != feedTeam.Name)
                    {
                        dbTeam.FileCode     = feedTeam.FileCode;
                        dbTeam.FirstSeason  = feedTeam.FirstYearOfPlay;
                        dbTeam.IsActive     = feedTeam.Active;
                        dbTeam.IsAllStar    = feedTeam.IsAllStarTeam;
                        dbTeam.TeamAbbr     = feedTeam.Abbreviation;
                        dbTeam.TeamCode     = feedTeam.TeamCode;
                        dbTeam.TeamFullName = feedTeam.Name;
                        dbTeam.TeamLocation = feedTeam.LocationName;
                        dbTeam.TeamName     = feedTeam.Name;
                    }
                }

                // ENTER SEASON BASED PROCESSING. CURRENT DATA CAN BE UPDATED ABOVE. SEASON BASED DATA SHOULD NEVER NEED TO BE UPDATED (FOR LEAGUE STRUCTURE)

                Model.VenueSeason dbVenueSeason = null;
                if (feedTeam.Venue?.Id != null && !dbVenueSeasons.TryGetValue(feedTeam.Venue.Id.Value, out dbVenueSeason))
                {
                    dbVenueSeason = new Model.VenueSeason
                    {
                        VenueID   = feedTeam.Venue.Id.Value,
                        Season    = this.Season,
                        VenueName = feedTeam.Venue.Name
                    };
                    dbVenueSeasons.Add(feedTeam.Venue.Id.Value, dbVenueSeason);
                    context.VenueSeasons.Add(dbVenueSeason);
                }

                if (!dbAssociationSeasons.TryGetValue(feedTeam.Sport.Id.Value, out Model.AssociationSeason dbAssociationSeason))
                {
                    dbAssociationSeason = new Model.AssociationSeason
                    {
                        Association     = dbAssociation,
                        Season          = this.Season,
                        AssociationName = feedTeam.Sport.Name
                    };
                    dbAssociationSeasons.Add(dbAssociation.AssociationID, dbAssociationSeason);
                    context.AssociationSeasons.Add(dbAssociationSeason);
                }

                Model.LeagueSeason dbLeagueSeason = null;
                if (feedTeam.League?.Id != null && !dbLeagueSeasons.TryGetValue(feedTeam.League.Id.Value, out dbLeagueSeason))
                {
                    dbLeagueSeason = new Model.LeagueSeason
                    {
                        League            = dbLeague,
                        Season            = this.Season,
                        LeagueName        = feedTeam.League.Name,
                        AssociationSeason = dbAssociationSeason
                    };
                    dbLeagueSeasons.Add(dbLeague.LeagueID, dbLeagueSeason);
                    context.LeagueSeasons.Add(dbLeagueSeason);
                }

                Model.LeagueSeason dbSpringLeagueSeason = null;
                if (feedTeam.SpringLeague?.Id != null && !dbLeagueSeasons.TryGetValue(feedTeam.SpringLeague.Id.Value, out dbSpringLeagueSeason))
                {
                    dbSpringLeagueSeason = new Model.LeagueSeason
                    {
                        League            = dbSpringLeague,
                        Season            = this.Season,
                        LeagueName        = feedTeam.SpringLeague.Name,
                        AssociationSeason = dbAssociationSeason
                    };
                    dbLeagueSeasons.Add(dbSpringLeague.LeagueID, dbSpringLeagueSeason);
                    context.LeagueSeasons.Add(dbSpringLeagueSeason);
                }

                Model.DivisionSeason dbDivisionSeason = null;
                if (feedTeam.Division?.Id != null && !dbDivisionSeasons.TryGetValue(feedTeam.Division.Id.Value, out dbDivisionSeason))
                {
                    dbDivisionSeason = new Model.DivisionSeason
                    {
                        Division     = dbDivision,
                        Season       = this.Season,
                        DivisionName = feedTeam.Division.Name,
                        LeagueSeason = dbLeagueSeason
                    };
                    dbDivisionSeasons.Add(dbDivision.DivisionID, dbDivisionSeason);
                    context.DivisionSeasons.Add(dbDivisionSeason);
                }

                Model.TeamSeason dbTeamSeason = null;
                if (!dbTeamSeasons.TryGetValue(feedTeam.Id, out dbTeamSeason))
                {
                    dbTeamSeason = new Model.TeamSeason
                    {
                        Team               = dbTeam,
                        Season             = this.Season,
                        AssociationSeason  = dbAssociationSeason,
                        LeagueSeason       = dbLeagueSeason,
                        DivisionSeason     = dbDivisionSeason,
                        VenueSeason        = dbVenueSeason,
                        FileCode           = feedTeam.FileCode,
                        FullName           = feedTeam.Name,
                        SpringLeagueSeason = dbSpringLeagueSeason,
                        TeamAbbr           = feedTeam.Abbreviation,
                        TeamCode           = feedTeam.TeamCode,
                        TeamLocation       = feedTeam.LocationName,
                        TeamName           = feedTeam.TeamName
                    };
                    dbTeamSeasons.Add(dbTeam.TeamID, dbTeamSeason);
                    context.TeamSeasons.Add(dbTeamSeason);
                }
            }

            var feedChildTeams = feed.Teams.Where(x => x.ParentOrgId.HasValue);

            foreach (var feedChildTeam in feedChildTeams)
            {
                var dbChildTeamSeason = dbTeamSeasons[feedChildTeam.Id];
                if (!dbTeamSeasons.TryGetValue(feedChildTeam.ParentOrgId.Value, out Model.TeamSeason dbParentTeamSeason))
                {
                    dbParentTeamSeason = new Model.TeamSeason
                    {
                        TeamID   = feedChildTeam.ParentOrgId.Value,
                        Season   = this.Season,
                        TeamName = feedChildTeam.ParentOrgName
                    };
                    dbTeamSeasons.Add(feedChildTeam.ParentOrgId.Value, dbParentTeamSeason);
                    context.TeamSeasons.Add(dbParentTeamSeason);
                }
                dbChildTeamSeason.ParentOrgSeason = dbParentTeamSeason;
            }

            context.SaveChanges();
        }
        public void Run(Model.MlbStatsContext context)
        {
            Feeds.PlayByPlayFeed feed;
            using (var client = new WebClient())
            {
                var    url     = Feeds.PlayByPlayFeed.GetFeedUrl(this.GameId);
                string rawJson = JsonUtility.GetRawJsonFromUrl(url);;
                if (rawJson == null)
                {
                    return;
                }
                feed = Feeds.PlayByPlayFeed.FromJson(rawJson);

                if (feed != null && feed.AllPlays != null && feed.AllPlays.Count > 0)
                {
                    var dbGame = context.Games.SingleOrDefault(x => x.GameID == this.GameId);
                    if (dbGame == null)
                    {
                        throw new NullReferenceException($"GAME NOT FOUND IN DB: {this.GameId}");
                    }
                    int season = dbGame.Season;

                    var dbTrajectoriesDict = context.HitTrajectoryTypes.ToDictionary(x => x.Code, y => y.HitTrajectoryTypeID);
                    var dbPitchResultsDict = context.PitchResultTypes.ToDictionary(x => x.Code, y => y.PitchResultTypeID);
                    var dbPitchTypesDict   = context.PitchTypes.ToDictionary(x => x.Code, y => y.PitchTypeID);

                    var dbPlaysDict          = context.GamePlays.Where(x => x.GameID == dbGame.GameID).ToDictionary(x => x.GamePlayIndex);
                    var dbPlayRunnersLookup  = context.GamePlayRunners.Include("FieldingCredits").Where(x => x.GamePlay.GameID == dbGame.GameID).ToLookup(x => x.PlayIndex);
                    var dbPlayPitchesLookup  = context.GamePlayPitches.Where(x => x.GamePlay.GameID == dbGame.GameID).ToLookup(x => x.GamePlay.GamePlayIndex).ToDictionary(x => x.Key, y => y.ToDictionary(z => (int)z.GamePlayEventIndex, z => z));
                    var dbPlayActionsLookup  = context.GamePlayActions.Where(x => x.GamePlay.GameID == dbGame.GameID).ToLookup(x => x.GamePlay.GamePlayIndex).ToDictionary(x => x.Key, y => y.ToDictionary(z => (int)z.GamePlayEventIndex, z => z));
                    var dbPlayPickoffsLookup = context.GamePlayPickoffs.Where(x => x.GamePlay.GameID == dbGame.GameID).ToLookup(x => x.GamePlay.GamePlayIndex).ToDictionary(x => x.Key, y => y.ToDictionary(z => (int)z.GamePlayEventIndex, z => z));

                    var feedPlayers = feed.AllPlays.Where(x => x.Matchup?.Pitcher != null && x.Matchup?.Batter != null)
                                      .SelectMany(x => new[] {
                        new {
                            IsHome   = x.About.HalfInning != "top",
                            PlayerId = x.Matchup.Batter.Id,
                            Name     = x.Matchup.Batter.FullName,
                            Link     = x.Matchup.Batter.Link
                        },
                        new {
                            IsHome   = x.About.HalfInning == "top",
                            PlayerId = x.Matchup.Pitcher.Id,
                            Name     = x.Matchup.Pitcher.FullName,
                            Link     = x.Matchup.Pitcher.Link
                        }
                    })
                                      .GroupBy(x => x.PlayerId)
                                      .Select(x => x.FirstOrDefault())
                                      .Where(x => x != null)
                                      .ToList();
                    var feedPlayerIds = feedPlayers.Select(x => x.PlayerId).ToList();
                    var dbPlayersDict = context.Players.Where(x => feedPlayerIds.Contains(x.PlayerID)).ToDictionary(x => x.PlayerID);
                    foreach (var feedPlayer in feedPlayers)
                    {
                        if (!dbPlayersDict.ContainsKey(feedPlayer.PlayerId))
                        {
                            int teamId   = feedPlayer.IsHome ? dbGame.HomeTeamID.Value : dbGame.AwayTeamID.Value;
                            var dbPlayer = new Player
                            {
                                PlayerID   = feedPlayer.PlayerId,
                                PlayerLink = feedPlayer.Link,
                                FullName   = feedPlayer.Name
                            };
                            dbPlayersDict.Add(dbPlayer.PlayerID, dbPlayer);
                            context.Players.Add(dbPlayer);
                            var pts = new PlayerTeamSeason {
                                Player = dbPlayer, TeamID = teamId, Season = season
                            };
                            context.PlayerTeamSeasons.Add(pts);
                        }
                    }
                    context.SaveChanges();


                    // TODO: IF ANY PLAY HAS CHANGED, DELETE ALL PLAYS AND REPROCESS FROM SCRATCH

                    Player pitcher = null;
                    foreach (var feedPlay in feed.AllPlays)
                    {
                        short playIndex = feedPlay.AtBatIndex;

                        byte           outCount = 0;
                        RunnerLocation startRunners = RunnerLocation.None, endRunners = RunnerLocation.None;
                        if (feedPlay.Runners != null && feedPlay.Runners.Count > 0)
                        {
                            outCount = (byte)feedPlay.Runners.Count(x => x.Movement.IsOut ?? false);
                            var feedRunnersByRunnerId = feedPlay.Runners.GroupBy(x => x.Details.Runner.Id).ToList();
                            foreach (var feedRunner in feedRunnersByRunnerId)
                            {
                                var start = (RunnerLocation)feedRunner.Select(x => GetRunnerLocationFromString(x.Movement?.Start, true)).Min(x => (int)x);
                                var end   = (RunnerLocation)feedRunner.Select(x => GetRunnerLocationFromString(x.Movement?.End, false)).Max(x => (int)x);
                                if (start != RunnerLocation.Home_End)
                                {
                                    startRunners = startRunners | start;
                                }
                                if (end != RunnerLocation.Home_End)
                                {
                                    endRunners = endRunners | end;
                                }
                            }
                        }

                        bool isNew    = !dbPlaysDict.TryGetValue(feedPlay.AtBatIndex, out GamePlay dbPlay);
                        if (isNew)
                        {
                            dbPlay = new GamePlay
                            {
                                Game          = dbGame,
                                GamePlayIndex = playIndex,
                                Season        = season,
                                IsInningTop   = string.Equals(feedPlay.About.HalfInning, "top"),
                                Inning        = feedPlay.About.Inning,
                            };
                            dbPlaysDict.Add(playIndex, dbPlay);
                            context.GamePlays.Add(dbPlay);
                        }

                        bool isUpdate = false;
                        if (!isNew)
                        {
                            isUpdate = CheckPlayForUpdate(feedPlay, dbPlay, outCount, startRunners, endRunners);
                        }

                        var feedPitcher = feedPlay.Matchup.Pitcher;
                        if (feedPitcher != null && (pitcher == null || pitcher.PlayerID != feedPitcher.Id))
                        {
                            pitcher = dbPlayersDict[feedPitcher.Id];
                        }

                        var feedBatter = feedPlay.Matchup.Batter;
                        if (!dbPlayersDict.TryGetValue(feedBatter.Id, out Player batter))
                        {
                            batter = dbPlayersDict[feedPlay.Matchup.Batter.Id];
                        }

                        if (isNew || isUpdate)
                        {
                            dbPlay.StartTime           = feedPlay.About.StartTime;
                            dbPlay.EndTime             = feedPlay.About.EndTime;
                            dbPlay.IsReview            = feedPlay.About.HasReview;
                            dbPlay.PlayType            = feedPlay.Result.Type;
                            dbPlay.PlayEvent           = feedPlay.Result.Event;
                            dbPlay.PlayEventType       = feedPlay.Result.EventType;
                            dbPlay.GamePlayDescription = feedPlay.Result.Description;
                            dbPlay.ScoreAway           = feedPlay.Result.AwayScore;
                            dbPlay.ScoreHome           = feedPlay.Result.HomeScore;
                            dbPlay.RunsScored          = feedPlay.Result.Rbi;
                            dbPlay.RunnerStatusStart   = startRunners;
                            dbPlay.RunnerStatusEnd     = endRunners;
                            dbPlay.BatterID            = batter.PlayerID;
                            dbPlay.PitcherID           = pitcher.PlayerID;
                            dbPlay.BatterHand          = feedPlay.Matchup.BatSide.Code[0];
                            dbPlay.PitcherHand         = feedPlay.Matchup.PitchHand.Code[0];
                            dbPlay.BatterSplit         = feedPlay.Matchup.Splits?.Batter;
                            dbPlay.PitcherSplit        = feedPlay.Matchup.Splits?.Pitcher;
                            dbPlay.Strikes             = (byte)feedPlay.Count.Strikes;
                            dbPlay.Balls     = (byte)feedPlay.Count.Balls;
                            dbPlay.OutsEnd   = (byte)feedPlay.Count.Outs;
                            dbPlay.OutsStart = (byte)(feedPlay.Count.Outs - outCount);
                        }

                        var dbPlayRunners = dbPlayRunnersLookup[playIndex];
                        var feedRunners   = feedPlay.Runners;
                        if (feedRunners != null && feedRunners.Count > 0)
                        {
                            foreach (var feedRunner in feedRunners)
                            {
                                if (feedRunner.Movement != null && feedRunner.Details != null)
                                {
                                    var runnerId      = feedRunner.Details.Runner.Id;
                                    var startLocation = GetRunnerLocationFromString(feedRunner.Movement.Start, true);
                                    var endLocation   = GetRunnerLocationFromString(feedRunner.Movement.Start, false);
                                    var dbPlayRunner  = dbPlayRunners.SingleOrDefault(x => x.RunnerID == runnerId && x.StartRunnerLocation == startLocation);

                                    bool isRunnerNew = false;
                                    if (dbPlayRunner == null)
                                    {
                                        isRunnerNew  = true;
                                        dbPlayRunner = new GamePlayRunner
                                        {
                                            GamePlay            = dbPlay,
                                            RunnerID            = runnerId,
                                            StartRunnerLocation = startLocation,
                                            EndRunnerLocation   = endLocation
                                        };
                                        if (dbPlay.Runners == null)
                                        {
                                            dbPlay.Runners = new List <GamePlayRunner>();
                                        }
                                        dbPlay.Runners.Add(dbPlayRunner);
                                    }

                                    bool isRunnerUpdate = false;
                                    if (!isNew)
                                    {
                                        isRunnerUpdate = CheckPlayRunnerForUpdate(feedRunner, dbPlayRunner, startLocation, endLocation);
                                    }

                                    if (isRunnerNew || isRunnerUpdate)
                                    {
                                        dbPlayRunner.IsEarned       = feedRunner.Details.Earned;
                                        dbPlayRunner.IsOut          = feedRunner.Movement.IsOut;
                                        dbPlayRunner.IsScore        = endLocation == RunnerLocation.Home_End;
                                        dbPlayRunner.IsTeamUnearned = feedRunner.Details.TeamUnearned;
                                        dbPlayRunner.MovementReason = feedRunner.Details.MovementReason;
                                        dbPlayRunner.OutLocation    = (dbPlayRunner.IsOut ?? false)
                                                                                                                                        ? GetRunnerLocationFromString(feedRunner.Movement.OutBase, false)
                                                                                                                                        : (RunnerLocation?)null;
                                        dbPlayRunner.OutNumber            = feedRunner.Movement.OutNumber;
                                        dbPlayRunner.PlayEvent            = feedRunner.Details.Event;
                                        dbPlayRunner.PlayEventType        = feedRunner.Details.EventType;
                                        dbPlayRunner.PlayIndex            = feedRunner.Details.PlayIndex;
                                        dbPlayRunner.PitcherResponsibleID = feedRunner.Details.ResponsiblePitcher?.Id;
                                        if (feedRunner.Credits != null && feedRunner.Credits.Count > 0)
                                        {
                                            if (dbPlayRunner.FieldingCredits == null)
                                            {
                                                dbPlayRunner.FieldingCredits = new List <GamePlayFieldingCredit>();
                                            }

                                            var dbCreditsToDelete = dbPlayRunner.FieldingCredits.ToList();                                             // EAGER LOAD
                                            foreach (var feedCredit in feedRunner.Credits)
                                            {
                                                var creditType = GetCreditTypeFromString(feedCredit.CreditCredit);
                                                var dbCredit   = dbPlayRunner.FieldingCredits.SingleOrDefault(x => x.FielderID == feedCredit.Player.Id && x.CreditType == creditType);
                                                if (dbCredit != null)
                                                {
                                                    dbCreditsToDelete.Remove(dbCredit);
                                                    dbCredit.CreditType = creditType;
                                                    dbCredit.FielderID  = feedCredit.Player.Id;
                                                    dbCredit.PosAbbr    = feedCredit.Position?.Abbreviation;
                                                    context.SaveChanges();
                                                }
                                                else
                                                {
                                                    dbCredit = new GamePlayFieldingCredit
                                                    {
                                                        PlayRunner   = dbPlayRunner,
                                                        PlayRunnerID = dbPlayRunner.GamePlayRunnerID,
                                                        CreditType   = creditType,
                                                        FielderID    = feedCredit.Player.Id,
                                                        PosAbbr      = feedCredit.Position?.Abbreviation
                                                    };
                                                    context.GamePlayFieldingCredits.Add(dbCredit);
                                                    context.SaveChanges();
                                                }
                                            }
                                            foreach (var dbCredit in dbCreditsToDelete)
                                            {
                                                context.GamePlayFieldingCredits.Remove(dbCredit);
                                                context.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        var dbPlayPitchesDict  = dbPlayPitchesLookup.ContainsKey(playIndex) ? dbPlayPitchesLookup[playIndex] : null;
                        var dbPlayActionsDict  = dbPlayActionsLookup.ContainsKey(playIndex) ? dbPlayActionsLookup[playIndex] : null;
                        var dbPlayPickoffsDict = dbPlayPickoffsLookup.ContainsKey(playIndex) ? dbPlayPickoffsLookup[playIndex] : null;
                        var feedPlayEvents     = feedPlay.PlayEvents;
                        if (feedPlayEvents != null && feedPlayEvents.Count > 0)
                        {
                            foreach (var feedPlayEvent in feedPlayEvents)
                            {
                                if (string.Equals(feedPlayEvent.Type, "pitch", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    bool isNewPitch = false;
                                    if (dbPlayPitchesDict == null || !dbPlayPitchesDict.TryGetValue(feedPlayEvent.Index, out GamePlayPitch dbPitch))
                                    {
                                        isNewPitch = true;
                                        dbPitch    = new GamePlayPitch
                                        {
                                            Batter             = batter,
                                            BatterID           = batter.PlayerID,
                                            Pitcher            = pitcher,
                                            PitcherID          = pitcher.PlayerID,
                                            GamePlay           = dbPlay,
                                            GamePlayID         = dbPlay.GamePlayID,
                                            GamePlayEventIndex = feedPlayEvent.Index,
                                            MlbPlayID          = feedPlayEvent.PlayId,
                                            PfxId = feedPlayEvent.PfxId
                                        };
                                        context.GamePlayPitches.Add(dbPitch);
                                    }

                                    bool isUpdatedPitch = false;
                                    // TODO: CHECK FOR UPDATES TO PITCH

                                    if (isNewPitch || isUpdatedPitch)
                                    {
                                        dbPitch.PitchNumber = feedPlayEvent.PitchNumber;

                                        dbPitch.Balls   = feedPlayEvent.Count?.Balls;
                                        dbPitch.Strikes = feedPlayEvent.Count?.Strikes;
                                        dbPitch.Outs    = feedPlayEvent.Count?.Outs;

                                        dbPitch.StartSpeed       = feedPlayEvent.PitchData?.StartSpeed;
                                        dbPitch.StrikeZoneBottom = feedPlayEvent.PitchData?.StrikeZoneBottom;
                                        dbPitch.StrikeZoneTop    = feedPlayEvent.PitchData?.StrikeZoneTop;
                                        dbPitch.EndSpeed         = feedPlayEvent.PitchData?.EndSpeed;
                                        dbPitch.NastyFactor      = feedPlayEvent.PitchData?.NastyFactor;

                                        dbPitch.P_A_X   = feedPlayEvent.PitchData?.Coordinates.A_X;
                                        dbPitch.P_A_Y   = feedPlayEvent.PitchData?.Coordinates.A_Y;
                                        dbPitch.P_A_Z   = feedPlayEvent.PitchData?.Coordinates.A_Z;
                                        dbPitch.P_PFX_X = feedPlayEvent.PitchData?.Coordinates.PFX_X;
                                        dbPitch.P_PFX_Z = feedPlayEvent.PitchData?.Coordinates.PFX_Z;
                                        dbPitch.P_P_X   = feedPlayEvent.PitchData?.Coordinates.P_X;
                                        dbPitch.P_P_Z   = feedPlayEvent.PitchData?.Coordinates.P_Z;
                                        dbPitch.P_V_X0  = feedPlayEvent.PitchData?.Coordinates.V_X0;
                                        dbPitch.P_V_Y0  = feedPlayEvent.PitchData?.Coordinates.V_Y0;
                                        dbPitch.P_V_Z0  = feedPlayEvent.PitchData?.Coordinates.V_Z0;
                                        dbPitch.P_X     = feedPlayEvent.PitchData?.Coordinates.X;
                                        dbPitch.P_X0    = feedPlayEvent.PitchData?.Coordinates.X0;
                                        dbPitch.P_Y     = feedPlayEvent.PitchData?.Coordinates.Y;
                                        dbPitch.P_Y0    = feedPlayEvent.PitchData?.Coordinates.Y0;
                                        dbPitch.P_Z0    = feedPlayEvent.PitchData?.Coordinates.Z0;

                                        dbPitch.P_BreakAngle    = feedPlayEvent.PitchData?.Breaks?.BreakAngle;
                                        dbPitch.P_BreakLength   = feedPlayEvent.PitchData?.Breaks?.BreakLength;
                                        dbPitch.P_Break_Y       = feedPlayEvent.PitchData?.Breaks?.BreakY;
                                        dbPitch.P_SpinDirection = feedPlayEvent.PitchData?.Breaks?.SpinDirection;
                                        dbPitch.P_SpinRate      = feedPlayEvent.PitchData?.Breaks?.SpinRate;

                                        dbPitch.P_Zone           = feedPlayEvent.PitchData?.Zone;
                                        dbPitch.P_TypeConfidence = feedPlayEvent.PitchData?.TypeConfidence;

                                        dbPitch.H_Coord_X = feedPlayEvent.HitData?.Coordinates?.CoordX;
                                        dbPitch.H_Coord_Y = feedPlayEvent.HitData?.Coordinates?.CoordY;

                                        dbPitch.H_Hardness      = feedPlayEvent.HitData?.Hardness;
                                        dbPitch.H_LaunchAngle   = feedPlayEvent.HitData?.LaunchAngle;
                                        dbPitch.H_LaunchSpeed   = feedPlayEvent.HitData?.LaunchSpeed;
                                        dbPitch.H_TotalDistance = feedPlayEvent.HitData?.TotalDistance;
                                        dbPitch.H_Location      = feedPlayEvent.HitData?.Location;

                                        dbPitch.HasReview = feedPlayEvent.Details?.HasReview;
                                        dbPitch.IsBall    = feedPlayEvent.Details?.IsBall;
                                        dbPitch.IsInPlay  = feedPlayEvent.Details?.IsInPlay;
                                        dbPitch.IsStrike  = feedPlayEvent.Details?.IsStrike;

                                        dbPitch.TimeSec = feedPlayEvent.StartTime.HasValue && feedPlayEvent.EndTime.HasValue
                                                                                                                        ? (short?)(feedPlayEvent.EndTime.Value - feedPlayEvent.StartTime.Value).TotalSeconds
                                                                                                                        : null;

                                        var trajectoryKey = feedPlayEvent.HitData?.Trajectory;
                                        dbPitch.H_TrajectoryTypeID = (!string.IsNullOrEmpty(trajectoryKey) && dbTrajectoriesDict.TryGetValue(trajectoryKey, out byte b1)) ? b1 : (byte?)null;

                                        var pitchResultKey = feedPlayEvent.Details?.Code;
                                        dbPitch.PitchResultTypeID = (!string.IsNullOrEmpty(pitchResultKey) && dbPitchResultsDict.TryGetValue(pitchResultKey, out byte b2)) ? b2 : (byte?)null;

                                        var pitchTypeKey = feedPlayEvent?.Details?.Type?.Code;
                                        dbPitch.PitchTypeID = (!string.IsNullOrEmpty(pitchTypeKey) && dbPitchTypesDict.TryGetValue(pitchTypeKey, out byte b3)) ? b3 : (byte?)null;
                                    }
                                }
                                else if (string.Equals(feedPlayEvent.Type, "action", StringComparison.InvariantCultureIgnoreCase))
                                {
                                }
                                else if (string.Equals(feedPlayEvent.Type, "pickoff", StringComparison.InvariantCultureIgnoreCase))
                                {
                                }
                                else
                                {
                                    throw new ArgumentException("UNEXPECTED PLAY EVENT TYPE");
                                }
                            }
                        }
                    }
                    context.SaveChanges();
                }
            }
        }
Esempio n. 11
0
        public void Run(Model.MlbStatsContext context)
        {
            var dbAssociations         = context.Associations.ToDictionary(x => x.AssociationID);
            var dbSeasonsByAssociation = context.AssociationSeasons.ToLookup(x => x.AssociationID, y => y.Season).ToDictionary(x => x.Key, y => y.ToList());
            var dbGameStatusIds        = context.GameStatusTypes.ToDictionary(x => x.GameStatusCode, y => y.GameStatusTypeID);
            var dbVenues         = context.Venues.ToDictionary(x => x.VenueID);
            var dbSeasonsByVenue = context.VenueSeasons.ToLookup(x => x.VenueID, y => y.Season).ToDictionary(x => x.Key, y => y.ToList());
            var dbTeams          = context.Teams.ToDictionary(x => x.TeamID);
            var dbSeasonsByTeam  = context.TeamSeasons.ToLookup(x => x.TeamID, y => y.Season).ToDictionary(x => x.Key, y => y.ToList());
            var dbAllGameIds     = context.Games.Select(x => x.GameID).ToList();

            var newTeams              = new List <Team>();
            var newTeamSeasons        = new List <TeamSeason>();
            var newVenues             = new List <Venue>();
            var newVenueSeasons       = new List <VenueSeason>();
            var newGames              = new List <Game>();
            var newAssociations       = new List <Association>();
            var newAssociationSeasons = new List <AssociationSeason>();

            foreach (var associationId in this.AssociationIds)
            {
                Console.WriteLine($"GameScheduleProcessor - {this.Year} - {associationId}");

                var dbGames = context.Games.Where(x => x.GameTime.Year == this.Year && x.AssociationID == associationId).ToDictionary(x => x.GameID);

                var url     = Feeds.GameScheduleFeed.GetFeedUrl(this.Year, associationId);
                var rawJson = JsonUtility.GetRawJsonFromUrl(url);
                var feed    = Feeds.GameScheduleFeed.FromJson(rawJson);

                if (feed?.Dates != null && feed.Dates.Count > 0)
                {
                    if (!dbAssociations.TryGetValue(associationId, out Model.Association dbAssociation))
                    {
                        dbAssociation = new Model.Association
                        {
                            AssociationID = associationId,
                            IsEnabled     = false
                        };
                        dbAssociations.Add(associationId, dbAssociation);
                        newAssociations.Add(dbAssociation);
                        dbSeasonsByAssociation[associationId] = new List <int>();
                    }

                    var feedSeasonOptions = feed.Dates.SelectMany(x => x.Games.Select(y => y.Season));
                    foreach (var feedSeasonOption in feedSeasonOptions)
                    {
                        if (!dbSeasonsByAssociation.ContainsKey(associationId))
                        {
                            dbSeasonsByAssociation[associationId] = new List <int>();
                        }
                        if (!dbSeasonsByAssociation[associationId].Contains(feedSeasonOption))
                        {
                            var dbAssociationSeason = new Model.AssociationSeason
                            {
                                AssociationID = associationId,
                                Season        = feedSeasonOption
                            };
                            newAssociationSeasons.Add(dbAssociationSeason);
                            dbSeasonsByAssociation[associationId].Add(feedSeasonOption);
                        }
                    }

                    foreach (var feedDate in feed.Dates)
                    {
                        if (feedDate?.Games != null && feedDate.Games.Count > 0)
                        {
                            foreach (var feedGame in feedDate.Games)
                            {
                                Model.Venue dbVenue = null;
                                if (feedGame.Venue?.Id != null && !dbVenues.TryGetValue(feedGame.Venue.Id, out dbVenue))
                                {
                                    dbVenue = new Model.Venue
                                    {
                                        VenueID   = feedGame.Venue.Id,
                                        VenueName = feedGame.Venue.Name,
                                        VenueLink = feedGame.Venue.Link
                                    };
                                    newVenues.Add(dbVenue);
                                    dbVenues.Add(dbVenue.VenueID, dbVenue);
                                }

                                Model.VenueSeason dbVenueSeason = null;
                                if (!dbSeasonsByVenue.ContainsKey(feedGame.Venue.Id))
                                {
                                    // THIS MAY BE THE FIRST VenueSeason.
                                    dbSeasonsByVenue[feedGame.Venue.Id] = new List <int>();
                                }
                                if (!dbSeasonsByVenue[feedGame.Venue.Id].Contains(feedGame.Season))
                                {
                                    dbVenueSeason = new Model.VenueSeason
                                    {
                                        VenueID   = feedGame.Venue.Id,
                                        Season    = feedGame.Season,
                                        VenueName = feedGame.Venue.Name
                                    };
                                    newVenueSeasons.Add(dbVenueSeason);
                                    dbSeasonsByVenue[feedGame.Venue.Id].Add(feedGame.Season);
                                }

                                var        feedAwayTeam = feedGame.Teams?.Away?.Team;
                                Model.Team dbAwayTeam   = null;
                                if (feedAwayTeam?.Id != null && !dbTeams.TryGetValue(feedGame.Teams.Away.Team.Id, out dbAwayTeam))
                                {
                                    // TODO: MAKE CALL TO TEAM API TO FILL IN FULL TEAM DATA
                                    dbAwayTeam = new Model.Team
                                    {
                                        TeamID       = feedAwayTeam.Id,
                                        IsActive     = false,
                                        IsAllStar    = false,
                                        FirstSeason  = null,
                                        TeamFullName = feedAwayTeam.Name,
                                        TeamName     = feedAwayTeam.Name
                                    };
                                    newTeams.Add(dbAwayTeam);
                                    dbTeams.Add(dbAwayTeam.TeamID, dbAwayTeam);
                                }

                                Model.TeamSeason dbAwayTeamSeason = null;
                                if (dbAwayTeam != null)
                                {
                                    if (!dbSeasonsByTeam.ContainsKey(feedAwayTeam.Id))
                                    {
                                        dbSeasonsByTeam[feedAwayTeam.Id] = new List <int>();
                                    }
                                    if (!dbSeasonsByTeam[feedAwayTeam.Id].Contains(feedGame.Season))
                                    {
                                        dbAwayTeamSeason = new Model.TeamSeason
                                        {
                                            TeamID        = feedAwayTeam.Id,
                                            Season        = feedGame.Season,
                                            FullName      = feedAwayTeam.Name,
                                            TeamName      = feedAwayTeam.Name,
                                            AssociationID = associationId
                                        };
                                        newTeamSeasons.Add(dbAwayTeamSeason);
                                        dbSeasonsByTeam[feedAwayTeam.Id].Add(feedGame.Season);
                                    }
                                }

                                var        feedHomeTeam = feedGame.Teams?.Home?.Team;
                                Model.Team dbHomeTeam   = null;
                                if (feedHomeTeam?.Id != null && !dbTeams.TryGetValue(feedGame.Teams.Home.Team.Id, out dbHomeTeam))
                                {
                                    // TODO: MAKE CALL TO TEAM API TO FILL IN FULL TEAM DATA
                                    dbHomeTeam = new Model.Team
                                    {
                                        TeamID       = feedHomeTeam.Id,
                                        IsActive     = false,
                                        IsAllStar    = false,
                                        FirstSeason  = null,
                                        TeamFullName = feedHomeTeam.Name,
                                        TeamName     = feedHomeTeam.Name
                                    };
                                    newTeams.Add(dbHomeTeam);
                                    dbTeams.Add(dbHomeTeam.TeamID, dbHomeTeam);
                                }

                                Model.TeamSeason dbHomeTeamSeason = null;
                                if (dbHomeTeam != null)
                                {
                                    if (!dbSeasonsByTeam.ContainsKey(feedHomeTeam.Id))
                                    {
                                        dbSeasonsByTeam[feedHomeTeam.Id] = new List <int>();
                                    }
                                    if (!dbSeasonsByTeam[feedHomeTeam.Id].Contains(feedGame.Season))
                                    {
                                        dbHomeTeamSeason = new Model.TeamSeason
                                        {
                                            TeamID        = feedHomeTeam.Id,
                                            Season        = feedGame.Season,
                                            FullName      = feedHomeTeam.Name,
                                            TeamName      = feedHomeTeam.Name,
                                            AssociationID = associationId
                                        };
                                        newTeamSeasons.Add(dbHomeTeamSeason);
                                        dbSeasonsByTeam[feedHomeTeam.Id].Add(feedGame.Season);
                                    }
                                }

                                if (!dbGames.TryGetValue(feedGame.GamePk, out Model.Game dbGame))
                                {
                                    if (dbAllGameIds.Contains(feedGame.GamePk))
                                    {
                                        // GAME IS RETURNED FOR MULTIPLE ASSOCIATIONS
                                        dbGame = context.Games.SingleOrDefault(x => x.GameID == feedGame.GamePk);
                                        if (dbGame == null)
                                        {
                                            dbGame = newGames.SingleOrDefault(x => x.GameID == feedGame.GamePk);
                                        }
                                        if (dbGame == null)
                                        {
                                            throw new NullReferenceException("GameID BUT NO GAME.... WTF?!");
                                        }
                                        if (dbGame.AltAssociationID.HasValue && dbGame.AltAssociationID.Value != associationId)
                                        {
                                            throw new ArgumentException(string.Format($"GAME HAS MORE THAN 2 ASSOCIATIONS. WTF?! - {feedGame.GamePk}"));
                                        }
                                        dbGame.AltAssociationID = associationId;
                                    }
                                    else
                                    {
                                        dbGame = new Model.Game
                                        {
                                            GameID                 = feedGame.GamePk,
                                            Season                 = feedGame.Season,
                                            AssociationID          = associationId,
                                            GameTypeID             = feedGame.GameType,
                                            AwayTeamID             = feedGame.Teams?.Away?.Team?.Id,
                                            HomeTeamID             = feedGame.Teams?.Home?.Team?.Id,
                                            VenueID                = feedGame.Venue.Id,
                                            GameTime               = feedGame.GameDate,
                                            GameStatus             = dbGameStatusIds[feedGame.Status.StatusCode],
                                            AwayScore              = (byte?)feedGame.Teams?.Away?.Score,
                                            HomeScore              = (byte?)feedGame.Teams?.Home?.Score,
                                            IsTie                  = feedGame.IsTie ?? false,
                                            IsDoubleHeader         = feedGame.IsDoubleHeader,
                                            DayGameNum             = (byte)feedGame.GameNumber,
                                            IsDayGame              = feedGame.IsDayGame,
                                            IsTBD                  = feedGame.Status?.StartTimeTbd ?? false,
                                            IsIfNecessary          = feedGame.IfNecessary,
                                            IfNecessaryDescription = feedGame.IfNecessaryDescription,
                                            ScheduledLength        = (byte)feedGame.ScheduledInnings,
                                            SeriesLength           = (byte?)feedGame.GamesInSeries,
                                            SeriesGameNum          = (byte?)feedGame.SeriesGameNumber,
                                            SeriesDescription      = feedGame.SeriesDescription,
                                            RecordSource           = feedGame.RecordSource,
                                            AwaySeriesNum          = (byte?)feedGame.Teams?.Away?.SeriesNumber,
                                            AwayWins               = (byte?)feedGame.Teams?.Away?.LeagueRecord?.Wins,
                                            AwayLosses             = (byte?)feedGame.Teams?.Away?.LeagueRecord?.Losses,
                                            IsAwaySplitSquad       = feedGame.Teams?.Away?.SplitSquad,
                                            HomeSeriesNum          = (byte?)feedGame.Teams?.Home?.SeriesNumber,
                                            HomeWins               = (byte?)feedGame.Teams?.Home?.LeagueRecord?.Wins,
                                            HomeLosses             = (byte?)feedGame.Teams?.Home?.LeagueRecord?.Losses,
                                            IsHomeSplitSquad       = feedGame.Teams?.Home?.SplitSquad,
                                            AltAssociationID       = null,
                                            RawSeason              = feedGame.RawSeason,
                                            RescheduledDate        = feedGame.RescheduleDate,
                                            RescheduledFromDate    = feedGame.RescheduledFrom,
                                            ResumeDate             = feedGame.ResumeDate,
                                            ResumedFrom            = feedGame.ResumedFrom
                                        };
                                        newGames.Add(dbGame);
                                        dbGames.Add(dbGame.GameID, dbGame);
                                        dbAllGameIds.Add(dbGame.GameID);
                                    }
                                }
                                else
                                {
                                    ;                                     // TODO: UPDATE GAME VALUES
                                }
                            }
                        }
                    }
                    context.SaveChanges();
                }
            }
            context.Associations.AddRange(newAssociations);
            context.Teams.AddRange(newTeams);
            context.Venues.AddRange(newVenues);
            context.SaveChanges();
            context.AssociationSeasons.AddRange(newAssociationSeasons);
            context.VenueSeasons.AddRange(newVenueSeasons);
            context.SaveChanges();
            context.TeamSeasons.AddRange(newTeamSeasons);
            context.SaveChanges();
            context.Games.AddRange(newGames);
            context.SaveChanges();
        }