LINQ to Entities - 方法无法识别

时间:2016-01-22 07:49:46

标签: c# linq-to-entities expression-trees

我遇到了对Queryable数据集执行查询的问题。 原始呼叫如下所示:

books = books.Where(b => (GetPropertyValue(b, filter.CategoryProperties.DbName) == null ? 0 : Convert.ToInt32(GetPropertyValue(b, filter.CategoryProperties.DbName))) < Convert.ToInt32(filter.Value));

这让我得到方法无法识别的错误。 这当然是由于调用GetPropertyValue所致。然后我读到我应该自己构建表达式树。 这导致以下代码:

public IQueryable<Books> GetExpression(IQueryable<Books> books, BookCategoryMapping filter)
    {
        var booksExpression = Expression.Parameter(typeof(Books), "b");
        var methodInfo = this.GetType().GetMethod("GetPropertyValue");
        var value = Expression.Call(methodInfo, booksExpression, Expression.Constant(filter.CategoryProperties.DbName));
        var left = Expression.Constant(value);
        var right = Expression.Constant(filter.Value);
        var expression = Expression.Equal(left, right);
        var whereExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { books.ElementType }, books.Expression, Expression.Lambda<Func<Books, bool>>(expression, new ParameterExpression[] { booksExpression }));
        return books.Provider.CreateQuery<Books>(whereExpression);
    }

唯一的问题是,我得到了同样的错误。似乎以下行只生成表达式而不是所述表达式的值。

var value = Expression.Call(methodInfo, booksExpression, Expression.Constant(filter.CategoryProperties.DbName));

非常感谢产生正确表达树的任何帮助: - )

编辑: 这是GetPropertyValue方法:

public static object GetPropertyValue(object obj, string name)
    {
        try
        {
            return obj.GetType().GetProperty(name)?.GetValue(obj, null);
        }
        catch (Exception ex)
        {
            LogManager.Log(LogLevel.Error, null, ex);
        }

        return obj;
    }

1 个答案:

答案 0 :(得分:1)

下面的方法生成Expression<Func<Book, bool>>,它确定Book的给定属性是否小于给定(常量)值。您在GetPropertyValue中当前具有的错误检查代码可能会被捕获ArgumentException替换,当您尝试为不存在的属性创建表达式时,它将被抛出。

请注意,我假设您正在访问的媒体资源属于真正的数字版,并且您只需要Convert.ToInt32调用此GetPropertyValue方法即可返回object

Expression<Func<Book, bool>> GenerateLessThanExpression(string propertyName, int value)
{
    var parameter = Expression.Parameter(typeof (Book));
    var property = Expression.Property(parameter, propertyName);
    var comparison = Expression.LessThan(property, Expression.Constant(value));

    return Expression.Lambda<Func<Book, bool>>(comparison, parameter);
}

以下是仅返回非常短书的示例用法:

var filter = GenerateLessThanExpression("Pages", 5);
var filtered = books.Where(filter);