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.
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();
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.
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:
- Your class defines a property whose name is “ID” or “Id”
- 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));
[KeyAttribute]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With