EntityFramework 6 How to get identity-field with reflection?

c# entity-framework entity-framework-6 reflection

Accepted Answer

The essential keys cannot, in my opinion, be obtained solely through introspection.

Let's first see how EF chooses the property(ies) that will serve as the primary key(s), regardless of their ranking or importance.

  • from zzzz-17 zzzz

The Entity Framework convention for primary keys is:

  1. Your class defines a property whose name is “ID” or “Id”
  2. or a class name followed by “ID” or “Id”

We may useGetProperties then compare the name of the property.

var key = type.GetProperties().FirstOrDefault(p => 
    p.Name.Equals("ID", StringComparison.OrdinalIgnoreCase) 
    || p.Name.Equals(type.Name + "ID", StringComparison.OrdinalIgnoreCase));
  • from zz-40 zz

We may useCustomAttributes and compare the type of the characteristic.

var key = type.GetProperties().FirstOrDefault(p => 
    p.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute)));
  • from zzz-60 zzz

The hardest one to complete is this.modelBuilder is condensed in theOnModelCreating even if we manage to save themodelBuilder Finding the key in a field or land is still challenging.HasKey everything is contained in its role. The code source can be checked. Additionally, everything in EF is reliant on ObjectContext, and once theObjectContext is invoked, such as this line of code,


then, as you can see using profiler, a connection to the database will be established. The source code extract can be found here.

public override ObjectContext ObjectContext
        return ObjectContextInUse;

public void Initialize()

Currently, as stated in these words, the only way to obtain the primary key(s) is through an object set, entity set, key member, etc.

var keyNames = set.EntitySet.ElementType.KeyMembers.Select(k => k.Name);
5/23/2017 11:54:07 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow