entity-framework-4.1ef-code-first

Entity Framework code first. Find primary key


How do I find which property of a class is the primary key of the Entity Framework Code First entity POCO?

Please note string matching for Id / class name + "Id" is a bad option. There must be some way to dig out the convention used by Entity Framework and reliably getting the key property.

Thanks in advance.


Solution

  • 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.