0

I'm trying to learn how to use Entity Framework to create my database. My data has a many-to-many relationship in it. To simplify, think of it as wanting to store the Lineups for every baseball game this year.

I have a Game class that holds specifics about the game (date, which teams, location, etc.). I have a Player class that holds specifics about each player. I then have a Lineup class that I expect to be a many-to-many join of these two tables.

The table I'm expecting (Lineup) would look like this:

GameId  int
PlayerId int

I'm not seeing how to get that to happen. Either I get a table that has GameId as PK and PlayerId as FK, or if I use the [Key] attribute, I get told there's no key set on the class.

Any thoughts on how to approach this? Or, is my only option really to create the DB first, then use EF to create the models?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291

1 Answers1

0

You don't create a class for the many-to-many table.

You put a

public virtual ICollection<Game> Games{ get; set; }

in the Player class. And a

public virtual ICollection<Player> Players { get; set; }

in the Game class. Entity Framework then understands this is a many-to-many and will create a GamePlayers table.

Do you need to put the players in order? If so, then you'll need to explicitly create a GamePlayers class with GameId, PlayerId, and Order, and have a one-to-many relationship to both the Game and Player classes.

RyanB
  • 757
  • 4
  • 11