4
votes

I am reverse engineering our db. I am using scaffold-dbcontext in the package manager console with the -force flag. I know for sure it is updating the files.

I have added a Primary key in the db though and when that didn't work I even added another Index:

enter image description here

The dbcontext that was created seems to have the code for the Primary Key:

modelBuilder.Entity<DealerDisclaimers>(entity =>
    {
        entity.HasKey(e => e.DealerDisclaimerId)
            .HasName("PK_DealerDisclaimers");

However, when I try to navigate to a page that would load that table it gives the following error:

InvalidOperationException: The entity type 'DealerDisclaimers' requires a primary key to be defined.

The DealerDisclaimers class the scaffold-dbcontext builds out looks like this:

public partial class DealerDisclaimers
    {
        public int DealerDisclaimerId { get; set; }
        public int DealerId { get; set; }
        public string GeneralDisclaimer { get; set; }
        public string LeaseDisclaimer { get; set; }

        public virtual Dealer Dealer { get; set; }
    }

Side note: If I add the [Key] attribute then it loads without the error. But I shouldn't have to manually add it, the scaffold-dbcontext command should prepare everything for me.

1
The answer to this question might help you: stackoverflow.com/questions/43503424/… - Anthony McGrath
It says "You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter." but I have a setter already, and the scaffold-dbcontext should be creating all this stuff automatically - Tyler
What does your DealerDisclaimers class look like? - Anthony McGrath
I added it to the original post - Tyler
@Samir I know it's a pretty old question, but did you find an answer? I have a PK in the database, I'm using scaffold-dbcontext with -DataAnnotations -Force flags, but the [Key] attribute is not created - Ish Thomas

1 Answers

-1
votes

Simply adding -DataAnnotations to the scaffold code added the key appropriately for me.

So my script looked like this:

Scaffold-DbContext "Server=MyServer;Database=MyDatabase;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Force -DataAnnotations