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

Linq .Where(type = typeof(xxx)) comparison is always false

我正在尝试分配 Entities class 中所有 DbSet 属性的 static List<PropertyInfo>

但是当代码运行时列表是空的,因为 .Where(x => x.PropertyType == typeof(DbSet)) 总是 returns false.

我尝试了 .Where(...) 方法的多种变体,例如 typeof(DbSet<>)Equals(...).UnderlyingSystemType 等,但 none 有效。

为什么在我的情况下 .Where(...) 总是 return 错误?

我的代码:

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....
}

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

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

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

.Where(x => IsDbSet(x.PropertyType))