Reputation: 13
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?
Upvotes: 1
Views: 1425
Reputation: 3239
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;
}
}
Upvotes: 1