I am trying to create a generic method that will retrieve an item by its id:
public T GetByID(int id)
{
return (T) context.GetObjectByKey(
new System.Data.EntityKey(context.DefaultContainerName + "." +
context.CreateObjectSet<T>().EntitySet.Name,
"ProductID", id));
}
Basically I am able to infer the entity name from T, however I have no idea how to figure out what the primary key is for an entity?
I ended up creating my own attribute and modifying the T4 template to place that attribute above the primary key column. Here are the steps I took:
Add the following above the [DataMember] attribute in the T4 template:
Create the PrimaryKeyAttribute:
Introduce a helper method to determine the primary key of an entity:
Finally write the generic GetByID as such: