Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in entity framework code first, how to use KeyAttribute on multiple columns

I'm creating a POCO model to use with entity framework code first CTP5. I'm using the decoration to make a property map to a PK column. But how can I define a PK on more then one column, and specifically, how can I control order of the columns in the index? Is it a result of the order of properties in the class?

Thanks!

like image 219
GilShalit Avatar asked Feb 09 '11 20:02

GilShalit


People also ask

What is meant by composite primary key in Entity Framework Code First?

Use the ColumnAttribute or the HasKey method to specify an order for composite primary keys. In order to use composite keys, Entity Framework requires you to define an order for the key properties. You can do this by using the Column annotation to specify an order.

How do I create a composite primary key in Entity Framework?

Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.


1 Answers

You can specify the column order in the attributes, for instance:

public class MyEntity {     [Key, Column(Order=0)]     public int MyFirstKeyProperty { get; set; }      [Key, Column(Order=1)]     public int MySecondKeyProperty { get; set; }      [Key, Column(Order=2)]     public string MyThirdKeyProperty { get; set; }      // other properties } 

If you are using the Find method of a DbSet you must take this order for the key parameters into account.

like image 67
Slauma Avatar answered Sep 23 '22 19:09

Slauma