0

I am getting data from an NBA API and in order to write the data to my database I need to create the DB object of PlayerGame with composite keys PlayerID and GameID I tried using two [key][column=] tags to define this but when attempting to add the migration I was given the error need to use fluent api. so after some googling I came up with the following code and now upon attempting a migration I am given the error message The entity type 'IdentityUserLogin' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'. I'm guessing it has to do with ApplicationDbCOntext inheriting from IdentityDbContext but I really have no clue what to do at this point. Please help!!

I have a class Player Game

public class PlayerGame
{

    [Required]
    public int PlayerID { get; set; }

    [ForeignKey ("PlayerID")]
    public Player Player { get; set; }


    [Required]
    public int GameID { get; set; }

    [ForeignKey ("GameID")]
    public Game Game { get; set; }

and DB Context

public class ApplicationDbContext : IdentityDbContext
{

    public DbSet<Player> Player {get; set; }

    public DbSet<Game> Game { get; set; }

    public DbSet<PlayerGame> PlayerGame { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.Entity<PlayerGame>()
            .HasKey(pg => new { pg.PlayerID, pg.GameID });
    }

1 Answer 1

1

This is actually very simple. Move the call to base method below your custom logic and it should work.

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<PlayerGame>()
        .HasKey(pg => new { pg.PlayerID, pg.GameID });

    base.OnModelCreating(builder); // <-- move this line to bottom
}

You should finish all your custom configurations before calling the base method. The base method is what is throwing that error

2
  • I have a class PlayerBet that was attached to PlayerGame How would I go about getting the PlayerGame object in PlayerBet via the composite key? May 4, 2021 at 4:22
  • Its hard to give a comprehensive answer without the full code but maybe somehting like this context.PlayerGame.Include(pg => pg.Bet).Find(playerID, gameID }). find gets the data and the include means it will be loaded along with PlayerGame and accepts the parameters in order you set them. Or you could do this context.PlayerGame.Where(pg => pg.PlayerID == playerID && pg.GameID == gameID).Select(pg => pg.PlayerBet }).FirstOrDefault(). Both has async versions so use them if possible May 4, 2021 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.