I am trying to create a generic method using EF4 to find the primary key of an object.
example
public string GetPrimaryKey()
{
...
}
>
There is a property on each EF4 entity called EntityKey
which contains an array of EntityKeyValues
(array is there in case of compound key).
You could reference this directly on your entity instance or create a generic helper method that does this under the covers. If I can test-drive some sample code, I'll post it up here.
Edit: The EntityKeyValue is a KeyValuePair
where the key
is the primary key field of the entity and the value
is the associated value.
E.g., I have an entity called Company
whose primary key is the field Symbol
.
var firstCompany = (from c in context.Companies select c).FirstOrDefault();
var kvp = firstCompany.EntityKey.EntityKeyValues[0];
// kvp shows {[Symbol, FOO]}
In my sandbox, I noticed this property was null
when I created the entity in code. But once I read the entity from the database, it was correctly populated. So, it appears that the EF4 concept of a primary key only comes in to play once it hits the database. Although, you are free to set it explicitly ahead of time, if you wish.