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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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