[Solved] EntityFramework Error: EntitySet [Entity Name] is based on type [Entity Name] that has no keys defined

smile
 
on Feb 26, 2021 10:21 PM
736 Views

I have created a class Student.cs and wrote the following code

After that i wrote the following command

PM: Enable-Migrations -ContextTypeName myApp.SchoolContext -Force

It is showing me following error EntitySet 'Students' is based on type 'Student' that has no keys defined

namespace myApp
{
    public class Student
    {
        //scalar
        public int StuId { get; set; }
        public string StuName { get; set; }
        public string StuFName { get; set; }
        public string StuPhone { get; set; }
        public string StuAddress { get; set; }
        public Nullable<int> StuType { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public byte[] Photo { get; set; }
        public decimal Height { get; set; }
        public float Weight { get; set; }

        //reference navigation
        public int GradeId { get; set; }
        public Grade Grade { get; set; }

    }

    public class Grade
    {
        public int GradeId { get; set; }
        public string GradeName { get; set; }
        public ICollection<Student> Student { get; set; }
    }
}

and in the SchoolContext.cs wrote the following code

public class SchoolDBContext : DBContext
{
    public SchoolDBContext() : base("name=cn")
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Grade> Grades { get; set; }
        
}

how to fix this error

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Feb 27, 2021 12:38 AM

Hi smile,

You need to set [Key] annotation attribute.

namespace myApp
{
    public class Student
    {
        //scalar
        [Key]
        public int StuId { get; set; }
        public string StuName { get; set; }
        public string StuFName { get; set; }
        public string StuPhone { get; set; }
        public string StuAddress { get; set; }
        public Nullable<int> StuType { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public byte[] Photo { get; set; }
        public decimal Height { get; set; }
        public float Weight { get; set; }
 
        //reference navigation
        public int GradeId { get; set; }
        public Grade Grade { get; set; }
 
    }
 
    public class Grade
    {
        [Key]
        public int GradeId { get; set; }
        public string GradeName { get; set; }
        public ICollection<Student> Student { get; set; }
    }
}