문제

The following is the code:

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

This code is a refactored code that if I break it to its object and property level it would take me repeating it hundred times all around my code project. According to my research in this site it has something to do with the SQL translation. But is there any work around where this code or its variant will work fine?

도움이 되었습니까?

해결책

The solution is to create an Expression that returns the specified property and pass that expression to Where:

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

GetExpression looks something like this:

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top