Search code examples
c#.net-core

.NET System.InvalidCastException issue when no cast should need to be applied


I have the following models:

[Table("league_seasons")]
public class LeagueSeason
{
    [Key]
    [Column("league_season_id")]
    public required int Id { get; set; }

    [ForeignKey("League")]
    [Column("league_id")]
    public required int LeagueId { get; set; }

    [ForeignKey("Season")]
    [Column("season_id")]
    public required int SeasonId { get; set; }

    [Column("yahoo_league_season_id")]
    public string? YahooLeagueSeasonId { get; set; }

    [Column("num_teams")]
    public required int NumTeams { get; set; }

    [Column("num_playoff_teams")]
    public int? NumPlayoffTeams { get; set; }

    [Column("num_weeks")]
    public required int NumWeeks { get; set; }

    [Column("rivalry_weeks")]
    public string? RivalryWeeks { get; set; }

    [Column("nut_cup_week")]
    public required int NutCupWeek { get; set; }

    [Column("avg_points")]
    public required double AvgPoints { get; set; }

    [Column("avg_moves")]
    public required double AvgMoves { get; set; }

    [Column("completed")]
    public required int Completed { get; set; }

    [Column("create_date")]
    public required DateTime CreateDate { get; set; }

    [Column("modify_date")]
    public required DateTime ModifyDate { get; set; }


    // Relationships
    public virtual required League League { get; set; }
    public virtual required Season Season { get; set; }
    public virtual required ICollection<Team> Teams { get; set; }
}

[Table("seasons")]
public class Season
{
    [Key]
    [Column("season_id")]
    public required int Id { get; set; }

    [Column("yahoo_season_id")]
    public int? YahooSeasonId { get; set; }

    [Column("name")]
    public required string Name { get; set; }

    [Column("start_date")]
    public required DateOnly StartDate { get; set; }

    [Column("end_date")]
    public required DateOnly EndDate { get; set; }

    [Column("create_date")]
    public required DateTime CreateDate { get; set; }

    [Column("modify_date")]
    public required DateTime ModifyDate { get; set; }

    // Relationships
    public virtual ICollection<LeagueSeason> LeagueSeasons { get; set; }

for the following tables in my database:

CREATE TABLE `league_seasons` (
    `league_season_id` INT(10) NOT NULL AUTO_INCREMENT,
    `league_id` INT(10) NOT NULL,
    `season_id` INT(10) NOT NULL,
    `yahoo_league_season_id` VARCHAR(50) NULL DEFAULT NULL COMMENT 'Classified as their league id' COLLATE 'utf8mb3_general_ci',
    `num_teams` INT(10) NOT NULL,
    `num_playoff_teams` INT(10) NULL DEFAULT NULL,
    `num_weeks` INT(10) NOT NULL,
    `rivalry_weeks` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb3_general_ci',
    `nut_cup_week` INT(10) NULL DEFAULT NULL,
    `avg_points` DECIMAL(20,6) NULL DEFAULT NULL,
    `avg_moves` DECIMAL(20,6) NULL DEFAULT NULL,
    `completed` TINYINT(3) NOT NULL DEFAULT '0',
    `create_date` DATETIME NULL DEFAULT 'CURRENT_TIMESTAMP',
    `modify_date` DATETIME NULL DEFAULT 'CURRENT_TIMESTAMP',
    PRIMARY KEY (`league_season_id`) USING BTREE,
    UNIQUE INDEX `league_id_season_id` (`league_id`, `season_id`) USING BTREE,
    INDEX `league_id` (`league_id`) USING BTREE,
    INDEX `season_id` (`season_id`) USING BTREE,
    INDEX `yahoo_league_season_id` (`yahoo_league_season_id`) USING BTREE
)
COLLATE='utf8mb3_general_ci'
ENGINE=InnoDB;

CREATE TABLE `seasons` (
    `season_id` INT(10) NOT NULL AUTO_INCREMENT,
    `yahoo_season_id` INT(10) NULL DEFAULT NULL,
    `name` YEAR NOT NULL,
    `start_date` DATE NOT NULL,
    `end_date` DATE NOT NULL,
    `create_date` DATETIME NULL DEFAULT 'CURRENT_TIMESTAMP',
    `modify_date` DATETIME NULL DEFAULT 'CURRENT_TIMESTAMP' ON UPDATE (CURRENT_TIMESTAMP),
    PRIMARY KEY (`season_id`) USING BTREE,
    UNIQUE INDEX `yahoo_season_id` (`yahoo_season_id`) USING BTREE
)
COLLATE='utf8mb3_general_ci'
ENGINE=InnoDB;

with the following code:

/// <summary>
/// Method that calculates league power rankings for a given season and returns a dictionary of manager_ids and power ranking score
/// </summary>
/// <param name="selectedLeague"></param>
/// <param name="year"></param>
/// <returns></returns>
public static Dictionary<int, double> CalculateLeaguePowerRankings(int selectedLeague, int? year = null)
int current_league_season_id = context.LeagueSeasons 
                .Include(ls => ls.Season)
                .Where(ls => ls.LeagueId == selectedLeague)
                .OrderByDescending(ls => ls.Season.Name)
                .Select(ls => ls.Id)
                .First();

Dictionary<int, double> power_rankings = Calculations.CalculateLeaguePowerRankings(selectedLeague, context.LeagueSeasons.Find(current_league_season_id).Season.Name);

However, the last line of that code throws the following exception with the Season relationship in that method parameter:

System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.'

When I add the following code:

int current_season_id = context.LeagueSeasons
    .Include(ls => ls.Season)
    .Where(ls => ls.Id == current_league_season_id)
    .Select(ls => ls.SeasonId)
    .First();
    
Season current_season = context.Seasons.Find(current_season_id);

Both current_league_season_id and current_season_id are returning valid integers identifiers with records that can be found in the database. Additionally, the current_season_id is the season_id associated with my test current_league_season_id.

I've tried modifying the current_season query to use .Where(...).FirstOrDefault() instead of .Find() but the results are the same.


Solution

  • `name` YEAR NOT NULL,
    
    [Column("name")]
    public required string Name { get; set; }
    

    You have defined the column as numeric in the database but as a string in your C#.

    Change your DB schema to have name as a string.