EntityFramework 6 How to get identity-field with reflection?

c# entity-framework entity-framework-6 reflection

Question

I have a generic method with type parameter T, where T is the type of entity in EF model. I need to get the name of identifying field in this type. I saw this article: Is there a way to get entity id-field's name by reflection or whatever? But I can't understand, what Tevin talking about when he talks about EntitySetBase and EntityTypeBase types. If EntityTypeBase is type of one of the entities in model, so then EF6 have no property KeyMembers.

1
16
5/23/2017 12:17:23 PM

Accepted Answer

I don't think it's possible to get the primary keys only by reflection.

First, let's find out how EF determine which property(ies) that will be primary key(s) regardless of the order / priority

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 can use GetProperties and compare the property name.

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

We can use CustomAttributes and compare the attribute type.

var key = type.GetProperties().FirstOrDefault(p => 
    p.CustomAttributes.Any(attr => attr.AttributeType == typeof(KeyAttribute)));

This is the one that's difficult to do, modelBuilder is encapsulated in the OnModelCreating and even if we save the modelBuilder somewhere as field/property, it's still difficult to extract the key from HasKey function, everything is encapsulated. You can check the source code. And everything in EF depends on ObjectContext and once the ObjectContext is called, for example this line of code,

((IObjectContextAdapter)context).ObjectContext

then a connection to the database will be made, you can check using profiler. And here is the code excerpt of the source code.

public override ObjectContext ObjectContext
{
    get
    {
        Initialize();
        return ObjectContextInUse;
    }
}

public void Initialize()
{
    InitializeContext();
    InitializeDatabase();
}

Therefore, currently the only possible way to get the primary key(s) is through object set, entity set, key members, etc as explained in this post

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


Related Questions





Related

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