I have the following class:
public class AuthContext : DbContext
{
public DbSet<Models.Permission> Permissions { get; set; }
public DbSet<Models.Application> Applications { get; set; }
public DbSet<Models.Employee> Employees { get; set; }
// ...
}
I created the extension method Clear() for type DbSet<T>. Using reflection I am able to inspect the instance of AuthContext and read all its properties of type DbSet<T> as PropertyInfo[]. How can I cast the PropertyInfo to DbSet<T> in order to call the extension method on it ?
var currentContext = new AuthContext();
...
var dbSets = typeof(AuthContext).GetProperties(BindingFlags.Public | BindingFlags.Instance);
dbSets.Where(pi =>
pi.PropertyType.IsGenericTypeDefinition &&
pi.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)).ToList()
.ForEach(pi = ((DbSet<T>)pi.GetValue(currentContext, null)).Clear()); // !!!THIS WILL NOT WORK