gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:24:42 24 4
gpt4 key购买 nike

我正在尝试创建一个通用方法,该方法将通过其 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com