2017-10-19 124 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