Linq .Where(type = typeof(xxx))比较总是假的

Tom*_*Tom 6 c# linq ef-code-first

我正在尝试在课堂上分配static List<PropertyInfo>所有DbSet属性Entities.

但是,当代码运行时,List为空,因为.Where(x => x.PropertyType == typeof(DbSet)) 始终返回false.

我试过多种变化的.Where(...)方法类似typeof(DbSet<>),Equals(...),.UnderlyingSystemType等,但没有工作.

为什么.Where(...)总是在我的情况下返回false?

我的代码:

public partial class Entities : DbContext
{
    //constructor is omitted

    public static List<PropertyInfo> info = typeof(Entities).getProperties().Where(x => x.PropertyType == typeof(DbSet)).ToList();

    public virtual DbSet<NotRelevant> NotRelevant { get; set; }
    //further DbSet<XXXX> properties are omitted....
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

由于DbSet是一个单独的类型,您应该使用更具体的方法:

bool IsDbSet(Type t) {
    if (!t.IsGenericType) {
        return false;
    }
    return typeof(DbSet<>) == t.GetGenericTypeDefinition();
}
Run Code Online (Sandbox Code Playgroud)

现在您的Where子句将如下所示:

.Where(x => IsDbSet(x.PropertyType))
Run Code Online (Sandbox Code Playgroud)