Click here to Skip to main content
15,885,757 members
Articles / Programming Languages / C#

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

9 Nov 2015CPOL1 min read 12.9K   2   2
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)


Proud Indian | Author | TEDx Speaker | Microsoft MVP | CodeProject MVP | Speaker | DZone Most Valuable Blogger| jsfiddler

My Website

taditdash.com

Programming Community Profiles

jsfiddle | Stack Overflow

Social Profiles

Facebook | Twitter | LinkedIn

Awards


  1. DZone Most Valuable Blogger
  2. Microsoft MVP 2014, 2015, 2016, 2017, 2018
  3. Code Project MVP 2014, 2015, 2016
  4. Star Achiever of the Month December 2013
  5. Mindfire Techno Idea Contest 2013 Winner
  6. Star of the Month July 2013

Comments and Discussions

 
GeneralNice finding. Pin
Ch Smrutiranjan9-Nov-15 20:22
Ch Smrutiranjan9-Nov-15 20:22 
GeneralRe: Nice finding. Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)9-Nov-15 22:00
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)9-Nov-15 22:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.