The problem is that the generic DbSet<TEntity> class does not inherit (hence cannot be cast to) the non generic DbSet.
I see two options.
If you know the namespace name of the entity class, you can use Type.GetType
to get the corresponding Type
which in turn can be used to call the non generic DbContext.Set method which returns a non generic DbSet
object, e.g.
string nameSpace = "MyEntities";
string name = "ParosLineas";
var type = Type.GetType($"{namespace}.{name}");
var dbSet = efContext.Set(type);
Another way is to use reflection to get the DbSet<T>
property as you are doung, but cast the result to IQueryable
. Then you can use the IQueryable.ElementType
to call the non generic Set
method as above:
string name = "ParosLineas";
var type = ((IQueryable)efContext.GetType().GetProperty(name).GetValue(efContext))
.ElementType;
var dbSet = db.Set(type);
The first method is preferable. First, because it uses less calls, and second, because does not require DbSet<T>
property in the context and does not assume that DbSet<T>
property name is the same as the entity class name.
ParosLineas
?