How to create an EntityKey in Entity Framework

They are 4 ways to create an EntityKey using an EntityKey class. EntityKey class has four overload constructors and of them, one overload constructor supports composite keys.

In this article, I will explain how to create EntityKey using the following two constructors.
  1. EntityKey(String, IEnumerable<KeyValuePair<String, Object>>)
  2. EntityKey(String, String, Object)

1.EntityKey(String, IEnumerable<KeyValuePair<String, Object>>)

To create an EntityKey using the above constructor, we need to pass entity set name and a generic KeyValuePair IEnumerable collection. Using this constructor, we can create composite keys.

code for creating an EntityKey

2.EntityKey(String, String, Object)

EntityKey with parameters

To the above constructor, we pass an entity set name and specific key name and key value. This example is one usage of EntityKey class. The below example code creates an instance of EntityKey using a specified key name, key value, and the qualified entity set name.

code for creating an instance of EntityKey