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

·

2 min read

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

Problem

When you design a model class for the entity, you define many properties including keys, if any. But how MVC would 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 for 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. 👌

Did you find this article valuable?

Support Tadit Dash by becoming a sponsor. Any amount is appreciated!