Primary key not found when scaffolding controller in MVC core

Viewed 11865

When trying to scaffold a controller I get the following error:

"There was an error running the selected code generator: 'The entity type 'Company.Models.Office' requires a primary key to be defined at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b_6-0()"

I am new to MVC Core but my understanding is that a primary key is defined by default as ID or classnameID. I have also tried adding the [Key] attribute and renaming the primary key to OfficeID. I have gone through a similar process with another class and did not run into this problem

public class Office
    {
        public int ID;
        public string Name;
        public int SiteID;

    }
6 Answers

I faced a similar issue while scafolding In Asp net core Mvc. Adding this to your Dbcontext file might help!!

protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Office>(entity =>
                {
                    entity.HasKey(x=>x.OfficeID);

                });
            }

Make sure to remove entity.HasNoKey(); from modelBuilder as well.

I found a similar error while scaffolding asp.net core MVC controller method. The error reported the same error that is in the title of this question.

Here is my POCO for the Model class I entered for Scaffolding an 'MVC Controller with Views, using Entity Framework'

I finally figured out what was missing. The [Key] attribute was present but the members of the POCO are NOT declared as public. DON'T FORGET YOUR PUBLIC KEYWORD!!

public class RiskLimit
{
    [Key]
    int Id { get; set; }
    DateTime BeginMappingDateTime { get; set; }
    DateTime? EndMappingDateTime { get; set; }
}

Once I changed the code to

public class RiskLimit
{
    [Key]
    public int Id { get; set; }
    public DateTime BeginMappingDateTime { get; set; }
    public DateTime? EndMappingDateTime { get; set; }
}

I just had this issue. I forgot to set a primary key in the SQL table.

I ended up deleting all the model classes, and recreating them using -

Scaffold-DbContext "Server=.\sqlexpress;Database=YOURDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Afterwards, I was able to create the controller.

First, make sure that your table contains primary key, then run following command, in order to create model class using EF Db first approach:

Scaffold-DbContext "Server=DESKTOP-48G00GJ;Database=AXITClassDesignEg;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f

Note : use -f at the end

Then check the DbContext file, that entity.Haskey is created. Go to the controller, right-click add scaffold. Done !!!

Related