0

以下是代碼:在這段代碼中是否存在一個從NHibernate生成NotSupportedException的工作?

list = query.Where(x => ((string)x.GetType() 
    .GetProperty(propertyName).GetValue(this, null)) 
     .EndsWith(filterValue)).ToList(); 

此代碼是一個重構的代碼,如果我打破它給它的對象和屬性水平,這使我重複這百倍各地我的代碼項目。根據我在這個網站的研究,它與SQL翻譯有關。但是有沒有在這個代碼或其變體可以正常工作的地方工作?

回答

3

的解決方案是創建一個返回指定屬性的表達和傳遞表達Where

var query = session.Query<YourType>(); 
list = query.Where(GetExpression<YourType>(propertyName, filterValue)).ToList(); 

GetExpression看起來是這樣的:

public static Expression<Func<T, bool>> GetExpression<T>(string propertyName, 
                string filterValue) 
{ 
    var parameter = Expression.Parameter(typeof(T)); 
    var property = Expression.Property(parameter, propertyName); 
    var method = typeof(string).GetMethod("EndsWith", new [] { typeof(string) }); 
    var body = Expression.Call(property, method, 
           Expression.Constant(filterValue)); 
    return (Expression<Func<T, bool>>)Expression.Lambda(body, parameter); 
} 
+1

非常感謝它的工作。非常非常感謝你。 – 2013-02-19 12:46:27

相關問題