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

时间:2017-10-19 19:36:34

标签: c# linq ef-code-first

我尝试在static List<PropertyInfo>课程中分配DbSetEntities个属性。

但是,当代码运行时,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....
}

1 个答案:

答案 0 :(得分:7)

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

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

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

.Where(x => IsDbSet(x.PropertyType))
相关问题