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