简体   繁体   中英

How to get DbSet object for any table with table's name as string from DbContext in C#

How to get DbSet object for any table with table's name as string from DbContext in C# using reflection like:-

public DbSet GetTableObject(string tableName){

//TODO

}

This function should return the DbSet object for given table name using reflection in C# with DbContext . How can we do that?

I don't understand why you need this, but I guess you are looking for something like this?

 public object GetTableObject(string tableName)
        {

            PropertyInfo[] properties = typeof(Datalayer.Model.MyContext).GetProperties();
            var prop = properties.FirstOrDefault(p => p.Name == tableName);

            using (var db = new Datalayer.Model.MyContext())
            {
                var table = prop?.GetValue(db);
                return table;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM