Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First from database not adding Key attribute

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

like image 884
Rafael Avatar asked Mar 19 '26 22:03

Rafael


2 Answers

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.

like image 174
Brandon.Staley Avatar answered Mar 23 '26 20:03

Brandon.Staley


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; }
like image 20
Rafael Avatar answered Mar 23 '26 22:03

Rafael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!