简体   繁体   中英

EntityFramework - Composite keys and foreign key

Im working on a project and I'm using Entity Framework with the code first approach. My first model, Player, has two string for its ids (I didnt choose that and I know its a bad approach) :

public class Player()
{

    [Key, Column(Order=0)]
    public string Name { get; set;}

    [Key, Column(Order=1)]
    public string TeamId { get; set;}

    public Stat PlayerStat { get; set;}
}

The class Stat :

public class Stat()
{

    [Key]
    public int Id { get; set;}

    // This property should set the name id of the player
    public string Name { get; set;}

    // This property should set the teamId of the player
    public string TeamId{ get; set;}

    [Required]
    public Player Player { get; set;}
}

The player class has a one-to-one relationship with the class stat, where the Stat class is optional to he player class, but the player class is required for the stat class.

My problem is, when I create a new migration with Entity Framework and I update the database, it creates 5 columns for the Stat table.

  • Id
  • Name
  • TeamId
  • Player_Name
  • Player_TeamId

The properties Name and TeamId in the class stat should only be there to set the values of the foreign keys, and should not create columns in the table. Is there a way to map the property Name to the generated column "Player_Name" and TeamId to "Player_TeamId" ?

You need to reference your foreign keys in the Stat class:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM