Home > OS >  Properties to Database Columns (C#, EF Core)
Properties to Database Columns (C#, EF Core)

Time:06-22

I have programmed a TicTacToe game in WPF, which works perfectly fine. Now, my task is to create a database which saves information about the gam each round it's been played.

=> so the database columns should look like this

GameScoreId || Player X || Player O || GameMode || Winner || Loser || Game Status

My GameScore Class looks like this:

public class GameScores
{
    private MainWindowViewModel? MainWindowViewModel = new MainWindowViewModel();
    private TicTacToeLogic? Game => MainWindowViewModel!.CurrentGame;
    public int? GameScoreId { get; set; }
    public string PlayerX => Game!.PlayerX.Name;
    public string PlayerO => Game!.PlayerO.Name;
    public Enum Mode
    {
        get
        {
            var mode = Game!.PlayerO switch
            {
                HumanPlayer => GameMode.HumanVsHuman,
                EasyCom => GameMode.HumanVsEasyBot,
                HardCom => GameMode.HumanVsHardBot,
                _ => throw new NotImplementedException(),
            };
            return mode;
        }
    }
    public string? Winner
    {
        get
        {
            if (Game!.GameOver && Game.GetFreeFields().Count is not 0)
                return Game.CurrentPlayer!.Name;

            return null;
        }
    }
    public string? Loser
    {
        get
        {
            if (Game!.GameOver && Game.GetFreeFields().Count is not 0)
                return Game.CurrentPlayer!.Enemy!.Name;

            return null;
        }
    }
    public Enum Status
    {
        get
        {
            if (Game!.GameOver && Game.GetFreeFields().Count is not 0)
            {
                return GameStatus.Win;
            }
            return GameStatus.Draw;
        }
    }
}

and my Context Class looks like this:

public class GameScoresContext : DbContext
{
    // table with gamescores
    public DbSet<GameScores>? GameScores { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Data Source=localhost;Initial Catalog=GameScoresDB;Integrated Security=True");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<GameScores>().HasKey(e => e.GameScoreId);
    }
}

}

After adding migration and updating the database on the NuGet Packet Manager Console, it creates a table on my Server which looks like this: enter image description here

Why aren't the properties (GameScores class) being added as columns to the database? Or how can I add the properties as columns to my database?

Cheers!

CodePudding user response:

the properties need to be mapped as well

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<GameScores>().HasKey(e => e.GameScoreId);
    modelBuilder.Entity<GameScores>().Property(e => e.PlayerX);
    ...
}
  • Related