Entity Framework 4: How to find the primary key?

前端 未结 4 709
萌比男神i
萌比男神i 2020-11-28 11:12

I am trying to create a generic method using EF4 to find the primary key of an object.

example

public string GetPrimaryKey()
{
    ...
}
         


        
4条回答
  •  醉酒成梦
    2020-11-28 11:59

    So I was finally able to find out how to get this to work. I wish I hadn't lost the link to the blog I read last night as I didn't write the code.

    public T GetByPrimaryKey(int id) where T : class
    {
        return (T)_db.GetObjectByKey(new EntityKey(_db.DefaultContainerName + "." + this.GetEntityName(), GetPrimaryKeyInfo().Name, id));
    }
    
    string GetEntityName()
    {
        string name = typeof(T).Name;
        if (name.ToLower() == "person")
            return "People";
        else if (name.Substring(name.Length - 1, 1).ToLower() == "y")
            return name.Remove(name.Length - 1, 1) + "ies";
        else if (name.Substring(name.Length - 1, 1).ToLower() == "s")
            return name + "es";
        else
            return name + "s";
    }
    
    private PropertyInfo GetPrimaryKeyInfo()
    {
        PropertyInfo[] properties = typeof(T).GetProperties();
        foreach (PropertyInfo pI in properties)
        {
            System.Object[] attributes = pI.GetCustomAttributes(true);
            foreach (object attribute in attributes)
            {
                if (attribute is EdmScalarPropertyAttribute)
                {
                    if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true)
                        return pI;
                }
                else if (attribute is ColumnAttribute)
                {
    
                    if ((attribute as ColumnAttribute).IsPrimaryKey == true)
                        return pI;
                }
            }
        }
        return null;
    }
    

    I hope this helps someone else. All I can say is that it should be a little clearer on how to do this.

提交回复
热议问题