Entity Framework Code First from database not adding Key attribute

1.9k views Asked by At

When generating code first classes from an existing database the KeyAttribute is not added to the property of primary key of the table.

All tables from the database have a single column int PK named Id, there are no composite keys

A form generator and other classes use this attribute via reflection for internal logic

Can I configure Entity Framework to add the KeyAttribute to primary key properties when regenerating the model classes?

or

I'll have to manually annotate all key properties via the MetadataType attribute and change my code to support metadata types?

Thanks

2

There are 2 answers

0
Brandon.Staley On BEST ANSWER

This is the correct behavior. See the snippet from https://msdn.microsoft.com/en-us/data/gg193958.aspx below.

One of the conventions that code first depends on is how it implies which property is the key in each of the code first classes. That convention is to look for a property named “Id”...

Meaning if you name your pk Id it will infer that Id is the pk.

0
Rafael On

Do not name primary key columns as 'Id'

For some reason, when the column name its 'Id', the Key attribute is not added by the code first from existing database wizard

This was the code generated with 'Id' column:

[Table("tabla")]
public partial class tabla
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

This was the code generated with just renaming 'Id' to 'llave'

[Table("tabla")]
public partial class tabla
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int llave { get; set; }