简体   繁体   English

EntityFramework-复合键和外键

[英]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) : 我的第一个模型Player是两个ID字符串(我没有选择它,我知道这是一个不好的方法):

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 : 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. 玩家类与类stat具有一对一的关系,其中Stat类对于玩家类是可选的,但是stat类需要玩家类。

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. 我的问题是,当我使用Entity Framework创建新迁移并更新数据库时,它将为Stat表创建5列。

  • Id ID
  • Name 名称
  • TeamId TeamId
  • Player_Name 选手姓名
  • Player_TeamId 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. 类stat中的Name和TeamId属性只能用于设置外键的值,而不能在表中创建列。 Is there a way to map the property Name to the generated column "Player_Name" and TeamId to "Player_TeamId" ? 有没有一种方法可以将属性Name映射到生成的列“ Player_Name”,将TeamId映射到“ Player_TeamId”?

You need to reference your foreign keys in the Stat class: 您需要在Stat类中引用外键:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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