Entity Type Has No Key Defined

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

Add Controller in Entity Framework

Entity Type Has No Key Defined

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.

Comments

  1. By real admiral

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *