While working on Entity Framework we face lot of problems. This article discusses and provides the solutions of a common error: ModelValidationException, Entity Type Has No Key Defined; one or more validation errors were detected during model generation.
Generally this type of errors occurred when we try to add a Controller in the project.
ModelValidationException
System.Data.Entity.EdmEntityType: EntityType “MyClass” has no key defined. Define the key for this EntityType


Some possible reasons and solutions are given bellow:
Reason 1:
Key is missing. All Entity Framework Model needs a key.
public class Customer { public string CustomerName { get; set; } }
Solution: Include a key. That means just use the code
public int ID {get;set;}
Reason 2:
Class name is not equal to ID member name.
public class CustomerClass { public int CustomerID {get;set;} }
Solution: Change CustomerID to ID, or change CustomerClass to Customer
Reason 3:
Member does not have getter/setter – it needs to be a property. If this isn’t the Key, you may see a NotSupportedException instead:
The specified type member ‘<name>’ is not supported in LINQ to Entities.
Only initializers, entity members, and entity navigation properties are supported.
public class Customer { public int CustomerID; }
Solution: add {get;set;}
public int CustomerID {get;set;};
Reason 4:
The ID member is not public
public class Customer { protected int ID {get;set;}; }
Solution: Member must be public.
public int ID {get;set;};
Reason 5:
There is confusion in Entity Framework. Multiple ID is present.
public class Customer { public int anID { get; set; } public int anotherID { get; set; } }
Solution: Just add [Key] to give Entity Framework a hint to clarify what is the primary key. You may include the namespace System.ComponentModel.DataAnnotations;
public class Customer { [Key] public int anID { get; set; } public int anotherID { get; set; } }
That’s all about the error entity type has no key defined.
nice solution.its working
Hi, I had the same problem with EF 6 but the problem was different of the others listing in this article, so you can add another reason 🙂 my problem was in the file xxx.Context.cs inside into the xxx.Context.tt, I don’t know why this file was not update when I added new tables to the Entity Model, so I addeed the references to the objects manually
public virtual DbSet AspNetRoles { get; set; } (for example)
And the error was solved.
Thank you so much for your clear explanation. It was very useful and helpful. Solved my problem.
so thanks admin
Thanks