How to select the correct DbSet in DbContext based on table name
Let's say I have a DbContext with the following DbSets
class Amimals : DbContext
{
public DbSet<Dog> Dogs { get; set; }
public DbSet<Cat> Cats { get; set; }
}
Inside each EntityTypeConfiguration I define a table for each DbSet, for example
class DogConfig : EntityTypeConfiguration
{
public DogConfig()
{
this.ToTable("DOG_TABLE");
...
}
}
Now, if I have the table name and DbContext, how can I grab and use the correct DbSet?
void foo()
{
string tableName = this.GetTableName();
using(Animals context = new Animals())
{
/* Made up solution */
DbSet animalContext = context.Where(c => c.TableName == tableName);
...
/* Do something with DbSet */
...
}
}
source to share
You can get DbSet from DbContext by Type
using the method DbContext.Set(Type entityType)
. Therefore, if you have the name of the model class as a string, you must do some mapping to the actual type of clr.
For example:
string tableName = "Cat";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == tableName);
if(type != null)
DbSet catContext = context.Set(type);
You can also get a type from a string using the fully quoted type name Type.GetType ('...')
If it's even easier if you can somehow save the config and use the generic method context.Set<T>()
.
source to share