Get the primary key value of an arbitrary entity in code first

前端 未结 3 536
小鲜肉
小鲜肉 2020-12-09 18:02

Is there such a method?

object GetPrimaryKeyValue(DbEntityEntry entry);

Or how should it be implemented?

3条回答
  •  情歌与酒
    2020-12-09 18:29

    I am also looking to find the Primary Key of an entity. I am using Generics in my repository so I don't know the Entity until runtime. The only way I have found to do this so far is with a sql statement.

    public abstract class GenericRepository : ApiController,IGenericRepository where T : class
    {
    
    
        string sqlstr = @"
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
            WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + CONSTRAINT_NAME), 'IsPrimaryKey') = 1
            AND TABLE_NAME = '" + typeof(T).ToString() + "' AND TABLE_SCHEMA = 'dbo'";
    
        private Entities _entities = new Entities();
    
    
        public  virtual IQueryable GetAll()
        {
            DbSqlQuery queryTest = _entities.Set().SqlQuery(sqlstr);
    

    This is just a pratial of the full class but hopefully shows the solution I am using.

提交回复
热议问题