Find a specified generic DbSet in a DbContext dynamically when I have an entity
The question does not specify EF version and the proposed answer does not work anymore for Entity Framework Core (in EF Core, DbContext
does not have a non-generic Set
method, at least at the date of this answer).
Yet you can still have a working extension method using Jon Skeet's answer to this question. My code is added below for convenience.
Update: Added the generic function call as well returning IQueryable<T>
thanks to the comment from Shaddix.
public static IQueryable Set(this DbContext context, Type T)
{
// Get the generic type definition
MethodInfo method = typeof(DbContext).GetMethod(nameof(DbContext.Set), BindingFlags.Public | BindingFlags.Instance);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(T);
return method.Invoke(context, null) as IQueryable;
}
public static IQueryable<T> Set<T>(this DbContext context)
{
// Get the generic type definition
MethodInfo method = typeof(DbContext).GetMethod(nameof(DbContext.Set), BindingFlags.Public | BindingFlags.Instance);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(typeof(T));
return method.Invoke(context, null) as IQueryable<T>;
}
DbContext
has a method called Set
, that you can use to get a non-generic DbSet
, such as:
var someDbSet = this.Set(typeof(SomeEntity));
So in your case:
foreach (BaseEntity entity in list)
{
cntx.Set(entity.GetType()).Add(entity);
}