Looking at code first, I see some examples that use [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
to denote a primary key, and other examples that use [Key]
.
I haven't been able to find a description of how the two compare.
Can someone tell me when/if I'd want to use one over the other?
One specifies an explicit Primary Key , the other specifies that it should be an identity field in that database (which depends on the provider). In a lot of cases, the Key will be an identity field.
DatabaseGeneratedOption.Identity
You can mark the non-key (non-id) properties as DB-generated properties by using the DatabaseGeneratedOption.Identity option. This specifies that the value of the property will be generated by the database on the INSERT statement. This Identity property cannot be updated.
Please note that the way the value of the Identity property will be generated by the database depends on the database provider. It can be identity, rowversion or GUID. SQL Server makes an identity column for an integer property.
The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database. The default convention creates a primary key column for a property whose name is Id or Id. The Key attribute overrides this default convention.
if you wanted to specify a non identity primary key, you may use something like this
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]