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
Please see Andras Zoltan’s answer for an explanation of what you are doing wrong.
However, if you use .NET 4.0, you don’t need to use reflection to call the method, you can simply use the new
dynamickeyword:I changed the cast from
DbSet<T>todynamicand changed the way the method is called.Because
Clearis an extension method, it can’t be called directly on thedynamictype, becausedynamicdoesn’t know about extension methods. But as extension methods are not much more than static methods, you can always change a call to an extension method to a normal call to the static method.Everything you have to do is to change
ExtensionClassto the real class name in whichClearis defined.