【问题标题】:set multiple foreign keys as primary keys in entity framework在实体框架中将多个外键设置为主键
【发布时间】:2015-06-07 14:34:47
【问题描述】:

我正在使用实体框架来管理我的 sql-server-ce 数据库。我希望我的表的主键由其他表的几个外键组成。我希望这样的事情能够奏效:

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' 没有定义键。定义 此 EntityType 的键。 Bills: EntityType: EntitySet 'Bills' 基于具有 没有定义键。

我怎样才能让我的表有一个由这三个外键组成的主键?

【问题讨论】:

    标签: c# sql entity-framework sql-server-ce


    【解决方案1】:

    您不能将导航属性用作 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 要求您定义键属性的顺序。您可以使用Column 注释来指定订单。此外,您需要使用 ForeignKey 数据注释来阐明您的意图,哪个导航属性表示它是外键的关系。

    【讨论】:

    • 感谢兄弟这个作品。如果您不自己创建 Id 属性,实体框架会自动为您创建它们。但显然,除非您自己创建 Id 属性并对其进行注释,否则注释将不起作用。
    猜你喜欢
    • 2022-11-19
    • 2023-04-11
    • 1970-01-01
    • 2011-07-20
    • 2017-01-06
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2010-10-03
    相关资源
    最近更新 更多