質問

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