c# - 如何获得 self 跟踪实体的主键?

标签 c# entity-framework ado.net 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));
}

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

最佳答案

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

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

    <#if (ef.IsKey(edmProperty)) {#>    
    [PrimaryKeyAttribute]
    <#}#>
    
  2. 创建 PrimaryKeyAttribute:

    [AttributeUsage(AttributeTargets.Property)]
    public class PrimaryKeyAttribute : Attribute
    {}
    
  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;
    }
    
  4. 最后像这样编写通用的 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/

相关文章:

c# - 你能拼凑出以下线索来帮助我读取 Winbond W83793 芯片的温度吗?

c# - 为什么会有 Nullable<T> 结构和 Nullable 类?

c# - 如何将 session 变量与 C# 中的字符串进行比较?

entity-framework - 如何从解决方案资源管理器中选择特定的实体图

c# - 将在 using 语句中返回关键字,保持连接打开?

c# - Windows Phone silverlight 8.1 Http NotificationChannel ChannelUri 更新未被击中

asp.net - 使用 XSLT 转换 Entity Framework EDMX 文件

c# - 如何使用 Entity Framework 处理可选表?

c# - 声明静态、非静态、私有(private)或公共(public)数据库上下文有什么含义?

.net 2.0 : What's the best way to deal with in-memory DataTables?