Set multiple foreign keys as primary keys in entity framework

I am using entity framework to manage my sql-server-ce database. I want my table primary key to be composed of multiple foreign keys to other tables. I was expecting something like this:

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; }
}

      

but this results in the following database migration error:

BillPrinter.Bill :: EntityType "Bill" has no key. Define a key for this EntityType. Accounts: EntityType: EntitySet "Accounts" are based on the "Bill" type, which has no keys defined.

how can I force my table to have a primary key consisting of these three foreign keys?

+3


source to share


1 answer


You cannot use navigation properties like PC. Navigation properties provide a way to navigate between the two entity types, but they do not represent FK relationships. You need to explicitly declare three additional properties to represent the FK of your relationship, for example in this model:

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; }
}

      



As you can see, when you have composite keys, Entity Framework requires you to define the order of the key properties. You can do this using an annotation Column

to indicate the order. Also, you need to use data annotation ForeignKey

to clarify your intent which navigation property is the relationship for which it is a foreign key.

+5


source







All Articles