在 entity framework 中设置多个外键为主键

set multiple foreign keys as primary keys in entity framework

我正在使用 entity framework 来管理我的 sql-server-ce 数据库。我希望我的 table 的主键由其他 table 的几个外键组成。我希望这样的东西能起作用:

class Bill{
    [Key]
    public virtual Customer Customer { get; set; }
    [Key]
    public virtual Era Era { get; set; }
    [Key]
    public virtual CompanyCode CompanyCode { get; set; }
    public long? Amount { get; set; }
}

但会导致以下数据库迁移错误:

BillPrinter.Bill: : EntityType 'Bill' has no key defined. Define the key for this EntityType. Bills: EntityType: EntitySet 'Bills' is based on type 'Bill' that has no keys defined.

如何让我的 table 拥有一个由这三个外键组成的主键?

您不能将导航属性用作 PK。导航属性提供了一种在两个实体类型之间导航关联的方法,但它们本身并不表示关系的 FK。您需要明确声明三个额外的属性来表示您的关系的 FK,就像在这个模型中一样:

public class Customer
{
  public int Id {get;set;}
  //...
}

public class Era 
{
  public int Id {get;set;}
  //...
}

public class CompanyCode 
{
  public int Id {get;set;}
  //...
}


public class Bill
{
  [Key] 
  [Column(Order=1)] 
  [ForeignKey("Customer")]
  public int CustomerId {get;set;}

  [Key] 
  [Column(Order=2)] 
  [ForeignKey("Era")]
  public int EraId {get;set;}


  [Key] 
  [Column(Order=3)] 
  [ForeignKey("CompanyCode")]
  public int CompanyCodeId {get;set;}
  //...
  public virtual Customer Customer { get; set; }
  public virtual Era Era { get; set; }
  public virtual CompanyCode CompanyCode { get; set; }
}

如您所见,当您有复合键时,Entity Framework requires you to define an order of the key properties. You can do this using the Column annotation to specify an order. Also, you need to use the ForeignKey 数据注释阐明您的意图,哪个导航 属性 表示它是外键的关系。