如何获取自我跟踪实体的主键?

e36*_*6M3 5 c# ado.net entity-framework entity-framework-4

我正在尝试创建一个通用方法,它将通过其id检索项目:

public T GetByID(int id)
{
    return (T) context.GetObjectByKey(
        new System.Data.EntityKey(context.DefaultContainerName + "." +
             context.CreateObjectSet<T>().EntitySet.Name, 
             "ProductID", id));
}
Run Code Online (Sandbox Code Playgroud)

基本上我可以从T推断实体名称,但是我不知道如何找出实体的主键是什么?

e36*_*6M3 5

我最终创建了自己的属性并修改了T4模板,将该属性放在主键列的上方.以下是我采取的步骤:

  1. 在T4模板中的[DataMember]属性上添加以下内容:

    <#if (ef.IsKey(edmProperty)) {#>    
    [PrimaryKeyAttribute]
    <#}#>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建PrimaryKeyAttribute:

    [AttributeUsage(AttributeTargets.Property)]
    public class PrimaryKeyAttribute : Attribute
    {}
    
    Run Code Online (Sandbox Code Playgroud)
  3. 引入帮助方法来确定实体的主键:

    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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 最后写下通用的GetByID:

    public T GetByID(int id)
    {
        return (T)context.GetObjectByKey(new EntityKey(context.DefaultContainerName 
                                            + "." + context.CreateObjectSet<T>().EntitySet.Name
                                            , GetPrimaryKey<T>(), id));            
    }
    
    Run Code Online (Sandbox Code Playgroud)