2014-06-10 59 views
0

我想將屬性傳遞給方法並搜索與給定值匹配的記錄。以下代碼不會拋出錯誤,但也不會返回任何數據 - 有史以來。我不知道問題是否設置列/屬性就是這樣,或者別的東西是錯誤的...代碼如下:對LINQ屬性使用變量

public virtual IList<ReceivingInspection> GetRecordsBySupplier(string property, string value) { 
    if (property.Length < 1 || value.Length < 1) return null; 
    var result = from ri in _receiveInspectRepository.Table 
       where ri.property == value 
       select ri; 
    return result.ToList(); 
} 
+2

我不希望這些代碼都無法編譯......至少,'ri.property'沒有使用'property'參數,這大概是你打算的。 –

+0

'ri'應該有一個名爲property的屬性嗎?這將有助於瞭解如何定義「ri」。 –

+0

我想通了 - 它沒有一個名爲屬性的屬性 - 我必須遍歷所有的屬性,看看它們是否相等。我不是爲什麼它正在編譯tho ...我使用數據映射器和'.property'不應該編譯。這就是爲什麼我感到困惑,並認爲我可以這樣做。 IDK – TJB4rn3s

回答

1

你應該遍歷項_receiveInspectRepository.Table和使用Reflection來得到property

像這樣的東西的價值:

Type t = ri.GetType(); 
PropertyInfo prop = t.GetProperty(property); 
if(prop.GetValue(ri) == value) 
{ 
    dostuff(); 
}