How do I select correct DbSet in DbContext based on table name
Another approach is below and work fine for me:
Type t = Type.GetType(Assembly.GetExecutingAssembly().GetName().Name + "." + "TableName");
DbSet dbset = dbcontext.Set(t);
You can get DbSet from DbContext by Type
using the method DbContext.Set(Type entityType)
. So if you have the model class name as string you should do some mapping to actual clr type.
For example:
string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == tableName);
DbSet catContent;
if(type != null)
catContext = context.Set(type);
You also can get type from string using Full Assembly Qualified Name Type.GetType(' ... ')
If will be even easier if you can store configurations somehow in generic way and use the generic context.Set<T>()
method.