2017-10-19 106 views
6

我试图在Entities类中为DbSet属性指定static List<PropertyInfo>Linq .Where(type = typeof(xxx))的比较始终为假

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

'DbSet'!='DbSet '...我会说这就是问题 –

+0

@ClaudioRedi是的,这是问题。网上有资源可以阅读差异吗? – Tom

回答

7

由于DbSet是一个独立的类型,你应该使用一个更具体的办法:现在

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

Where条款看起来就像这样:

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

代码中的错字:'Type.GetGenericTypeDefinition'不带任何参数。 – pinkfloydx33

+0

@ pinkfloydx33你是对的,非常感谢你!欢迎您编辑代码,特别是当您看到这样的愚蠢错误时。 – dasblinkenlight