Transformer
Transformer

Reputation: 7429

EF database first code generation missing Key and data annotation

For EF 6.1 and above, when I add/reverse engineer-Entity model model/code generation in VS15 & Sql-Server 2k16 Database my entities are missing both Id, and auto increment data-annotations. Saw this and this Question on SO, but no answers, just that its a bug, I am seeking an option to generate the PK Key, Auto Increment.

Question: How can I ensure, that the Id key & Auto-increment options are added to the entities during the code generation? There are no data annotations except on the foreign keys! Can I also get EF to generate Composite keys?

What I did: In the database, I added the Set primary key on the [Id] col as int, I also set Identity true, seed 1, auto increment 1

E.g. missing primary key


//E.g. Reverse Eng. Generated code from ASP table 
public partial class AspNetUsers
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public AspNetUsers()
    {
        this.AspNetUserClaims = new HashSet<AspNetUserClaims>();
        this.AspNetUserLogins = new HashSet<AspNetUserLogins>();
        this.AspNetRoles = new HashSet<AspNetRoles>();
    }
    // Missing Primary Key
    public string Id { get; set; }
    public Nullable<int> IdNumber { get; set; } ...

E.g. 2 Missing both Primary Key & Auto Increment

public partial class AuditNetEvent
{
    //Reverse Generated code missing Primary Key & Auto Increment
    public bigint Id { get; set; }
    public System.DateTime InsertedDate { get; set; }

Upvotes: 4

Views: 1403

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109080

It seems that the tooling doesn't add annotations when the default conventions make them redundant. For an Id column the default is that it's PK and identity. I tried with a table not matching the conventions (deviating PK column name and no identity) and the annotations were added:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CstId { get; set; }

Upvotes: 3

Related Questions