Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

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

9 Nov 2015CPOL1 min read 13.4K  
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’

C#
public int Id { get; set; }

OR

C#
public int EntityNameId { get; set; }

Using [Key] Attribute

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

C#
[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. :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)