Primary key not found when scaffolding controller in MVC core

不问归期 提交于 2020-07-07 11:17:09

问题


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 went 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;

    }

回答1:


I'm not sure if this will resolve your issue, but maybe try the following. It sounds similar to what you described already, however I've posted it anyway just to be sure.

public class Office
{
    [Key]
    public int OfficeID { get; set; }
    public string Name { get; set; }
    public int SiteID { get; set; }
}

You should be aware that it doesn't really matter what your primary key is called. However, for easiness and following standards, you should call it either 'ID' or the table/class name plus 'ID'.

Also, have you tried restarting Visual Studio and your PC? Sometimes I find that this is the only way to resolve some compile time errors.




回答2:


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);

                });
            }



回答3:


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




回答4:


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; }
}


来源:https://stackoverflow.com/questions/45468959/primary-key-not-found-when-scaffolding-controller-in-mvc-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!