How to get first EntityKey Name for an Entity in EF4

后端 未结 4 1274
死守一世寂寞
死守一世寂寞 2021-02-06 15:21

How can I get the 1st EntityKey name for an Entity for Entity Framework 4 because I\'m building a repository system and I wanted to get an item by Id (which is the primary key o

4条回答
  •  星月不相逢
    2021-02-06 15:57

    public static string GetPrimaryKeyName(this object entity)
       {
           var prop = entity.GetType().GetProperties().Where(x =>x.GetCustomAttributes(false).Where(y => y is ColumnAttribute&&((ColumnAttribute)y).IsPrimaryKey == true).Any()).FirstOrDefault();
              if (prop != null)
                  return prop.Name;
              return string.Empty;
    
       }
    

提交回复
热议问题