我正在尝试创建一个通用方法,该方法将通过其 id 检索项目:
public T GetByID(int id)
{
return (T) context.GetObjectByKey(
new System.Data.EntityKey(context.DefaultContainerName + "." +
context.CreateObjectSet<T>().EntitySet.Name,
"ProductID", id));
}
基本上我可以从 T 推断出实体名称,但是我不知道如何找出实体的主键是什么?
最佳答案
我最终创建了自己的属性并修改了 T4 模板以将该属性放置在主键列之上。以下是我采取的步骤:
在 T4 模板中的 [DataMember] 属性上方添加以下内容:
<#if (ef.IsKey(edmProperty)) {#> [PrimaryKeyAttribute] <#}#>
创建 PrimaryKeyAttribute:
[AttributeUsage(AttributeTargets.Property)] public class PrimaryKeyAttribute : Attribute {}
引入一个辅助方法来确定实体的主键:
private string GetPrimaryKey<K>() { 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; }
最后像这样编写通用的 GetByID:
public T GetByID(int id) { return (T)context.GetObjectByKey(new EntityKey(context.DefaultContainerName + "." + context.CreateObjectSet<T>().EntitySet.Name , GetPrimaryKey<T>(), id)); }
关于c# - 如何获得 self 跟踪实体的主键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3451046/