65.9K
CodeProject is changing. Read more.
Home

EntityType: EntitySet ‘[Entity Name]’ is Based on Type ‘[Entity Name]’ that Has No Keys Defined

Nov 9, 2015

CPOL

1 min read

viewsIcon

13497

EntityType: EntitySet ‘[Entity Name]’ is Based on Type ‘[Entity Name]’ that has no keys defined

So, the exception completely indicates that it is not able to find a Key in model, which is defined in database for that entity.

Problem

When you design a model class for the entity, you define many properties including keys, if any. But how would MVC know that some property is a key and some other is a normal? There should be some rule, right? Yes, there is. And if you don’t follow that rule, you would definitely get the below exception.

EntityType: EntitySet '[Entity Name]' is based on type 
'[Entity Name]' that has no keys defined.

Solution

MVC will automatically recognize an entity’s Key if it follows the convention ‘Id’ or ‘EntityNameId’. Additionally, the entity must expose this as a PROPERTY AND it must be PUBLIC. If you don’t follow the convention, then you need to explicitly indicate that particular property as a Key by using an annotation. Let’s explore more below.

Example

Convention ‘Id’ or ‘EntityNameId’

public int Id { get; set; }

OR

public int EntityNameId { get; set; }

Using [Key] Attribute

Just put [Key] on top of your property (which is presenting primary key). Something like this.

[Key]
public int AnyName { get; set; }

Hope this Helps !!!

If you landed on this page by searching the issue somewhere, then I would like you to comment here if you have more queries or doubts. Thanks for reading the blog. Share if you care. :)