Entity Framework code first. Find primary key

You can ask mapping metadata to get names of key properties (there can be more then one):

ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<YourEntity> set = objectContext.CreateObjectSet<YourEntity>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
                                            .KeyMembers
                                            .Select(k => k.Name);

Once you have key names you can use reflection to access their values.

As you can see the approach reverts back to ObjectContext API because DbContext API is only for simple scenarios where you don’t bother with such details like mapping metadata.

Leave a Comment