Entity Type Has No Key Defined

匆匆过客 提交于 2019-12-09 14:57:34

问题


Another 'Entity Type 'x' has no key defined' question, but I've set the [Key] attribute on a property so I'm a bit confused.

Here's my entity and context classes:

namespace DoctorDB.Models
{
    public class Doctor
    {
        [Key]
        public string GMCNumber;
        [Required]
        public string givenName;
        [Required]
        public string familyName;
        public string MDUNumber;
        public DateTime MDUExpiry;
        public string MDUCover;
    }

    public class DoctorContext : DbContext
    {
        public DbSet<Doctor> Doctors { get; set; }
    }
}

When I go to create my controller, I've selected to create it with the Entity Framework methods using this entity and context:

and I get this error:

My only thought is whether you can't successfully use [Key] on a string property. If you can't then fair enough, I'll work round it, but I'd be grateful if someone could confirm this one way or the other.


回答1:


You need to change GMCNumber to a property not a field.




回答2:


To help clarify, this line:

public string GMCNumber;

needs to become:

public string GMCNumber { get; set; }




回答3:


I encountered the same error message when I had defined the property as private.




回答4:


I ran into this post after facing a similar issue today. The problem was that I was attempting to create the scaffold after adding the [Key] attribute to my model and without compiling. Once I compiled with the [Key] attribute the scaffolding generated just fine.



来源:https://stackoverflow.com/questions/6290511/entity-type-has-no-key-defined

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