我有以下的类:
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; }
// ...
}
我为类型DbSet<T>
创建了扩展方法Clear()
。使用反射技术,我能够检查AuthContext
实例,并将所有类型为DbSet<T>
的属性读取为PropertyInfo[
]。如何将PropertyInfo
强制转换为DbSet<T>
,以便在其上调用扩展方法?
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
!!!THIS WILL NOT WORK
时,你到底是什么意思?会发生什么? - Andras ZoltanClear()
方法的签名(不需要方法体),以帮助 @Daniel Hilgarth 和我澄清一些问题吗? :) - Andras Zoltanpi.PropertyType.IsGenericTypeDefinition
在你那里为什么不会失败。请参见此链接。 - Veverke