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
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With