6
string tableName = "TblStudents";
Dictionary<string, Type> myDictionary = new Dictionary<string, Type>()
{
    { "TblStudents", typeof(TblStudent) },
    { "TblTeachers", typeof(TblTeacher) }
};

// Context always same
DBContext dbContext = new DBContext();
DbSet dbSet = dbContext.Set(myDictionary[tableName]);

Above code is from this post where I can DbSet dynamically. How can I make this work in Entity Framework Core?

I get an error at

DbSet dbSet = dbContext.Set(myDictionary[tableName]);

seems like Set method has been changed in the new version.

Help is appreciated.

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
bbusdriver
  • 1,411
  • 3
  • 24
  • 51

1 Answers1

3

If you're trying to get the DbSet<TEntity> by TEntity, use:

var dbSet = dbContext.Set<TEntity>();

If you want to call that method based off a string name and your dictionary, you'll have to use reflection.

EF Core does not appear to have a non-generic DbSet so you'll have to use one of the non-generic interfaces such as IQueryable and I'd include a Func that you can invoke to get the IQueryable instead of just the type if you insist on going the dictionary mapping route. For example:

var myDictionary = new Dictionary<string, Func<DbContext, IQueryable>>()
{
    { "TblStudents", ( DbContext context ) => context.Set<TblStudent>() }
};

var dbSet = myDictionary[ "TblStudents" ].Invoke( dbContext );
Moho
  • 14,442
  • 1
  • 28
  • 30
  • Thanks for your answer. Now if I for-loop `dbSet`, I can't get the property inside `dbSet` since it's a type of `IQueryable`. How do I solve this? – bbusdriver Oct 04 '18 at 04:43
  • get what property? If `IQueryable` doesn't provide what you need, use the interface that does. I'm not sure what you're trying to accomplish. – Moho Oct 04 '18 at 05:22
  • What if I want to use `.Add` or `.Remove` ... Looks like both methods do not belong to any interface ... I hope that I'm wrong! – bunjeeb Jun 23 '21 at 09:41