Given an entity framework 4.0 code first entity
public class MyEntity
{
[Key]
public int MyEntityId { get; set; }
}
Is there a way to retrieve the value of the property decorated with the [Key] attribute without knowing the property's name?
public class KeyReader<TEntity> : where TEntity : class
{
public int GetKeyValue(TEntity entity){
//get key value for entity
}
}
UPDATE
I have a DBContext, so I can use the following code:
var objectContext = ((IObjectContextAdapter) myContext).ObjectContext;
objectContext.ObjectStateManager.GetObjectStateEntry(entity).EntityKey.EntityKeyValues;
However, this only works after the entity has been added or attached to the DBContext. The issue is that I wanted to use dynamic knowledge of the key and its value to determine whether an insert or update should be performed and thus whether to add or attach it to the context. By the time this code becomes possible, this is too late.
I have edited the question title to reflect this.
Any further thoughts?