Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework 6 How to get identity-field with reflection?

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.

like image 652
Jonik Avatar asked Aug 05 '14 14:08

Jonik


People also ask

How do I get identity value in EF core?

EF execute each INSERT command followed by SELECT scope_identity() statement. SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. The above example will execute the following SQL in the database. WHERE @@ROWCOUNT = 1 AND [StudentID] = scope_identity();

What is include in EntityFramework?

Entity Framework Classic Include The Include method lets you add related entities to the query result. In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.


1 Answers

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

  • By Convention

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));
  • By [KeyAttribute]

We can use CustomAttributes and compare the attribute type.

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

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);
like image 186
Yuliam Chandra Avatar answered Sep 22 '22 21:09

Yuliam Chandra