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.
C# – EntityFramework 6 How to get identity-field with reflection
c++entity-frameworkentity-framework-6reflection
Related Question
- C# – How to get a consistent byte representation of strings in C# without manually specifying an encoding
- C# – Get property value from string using reflection
- C# – How to determine if a type implements an interface with C# reflection
- C# – Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework
- C# – ASP.NET MVC 5 – Identity. How to get current ApplicationUser
- C# – Why not inherit from List
- C# – ASP.NET MVC – Attaching an entity of type ‘MODELNAME’ failed because another entity of the same type already has the same primary key value
Best Solution
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
We can use
GetProperties
and compare the property name.[KeyAttribute]
We can use
CustomAttributes
and compare the attribute type.This is the one that's difficult to do,
modelBuilder
is encapsulated in theOnModelCreating
and even if we save themodelBuilder
somewhere as field/property, it's still difficult to extract the key fromHasKey
function, everything is encapsulated. You can check the source code. And everything in EF depends onObjectContext
and once theObjectContext
is called, for example this line of code,then a connection to the database will be made, you can check using profiler. And here is the code excerpt of the source code.
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