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:
<#if (ef.IsKey(edmProperty)) {#> [PrimaryKeyAttribute]
<#}#>
- Create the PrimaryKeyAttribute:
[AttributeUsage(AttributeTargets.Property)]
public class PrimaryKeyAttribute : Attribute
{}
- Introduce a helper method to determine the primary key of an entity:
private string GetPrimaryKey()
{
string primaryKey = string.Empty;
PropertyInfo[] entityProperties = typeof(K).GetProperties();
foreach (PropertyInfo prop in entityProperties)
{
object[] attrs = prop.GetCustomAttributes(false);
foreach (object obj in attrs)
{
if (obj.GetType() == typeof(PrimaryKeyAttribute))
{
primaryKey = prop.Name;
break;
}
}
}
if (string.IsNullOrEmpty(primaryKey))
throw new Exception("Cannot determine entity's primary key");
return primaryKey;
}
- Finally write the generic GetByID as such:
public T GetByID(int id)
{
return (T)context.GetObjectByKey(new EntityKey(context.DefaultContainerName
+ "." + context.CreateObjectSet().EntitySet.Name
, GetPrimaryKey(), id));
}