我遇到了Ravendb session.Query.Where()的问题。 当我像这样使用它时,它可以完美地工作并返回用户名为'John'的所有UserIdentitiy:
users = session.Query<UserIdentity>().Where(x => x.UserName == "John").ToList();
但是当我尝试将Expression作为变量发送到Where方法时,它会以静默方式失败并且不返回任何内容。
Expression<Func<UserIdentity, bool>> whereClause = x => x.UserName == "John";
using (var session = _store.OpenSession())
{
users = session.Query<UserIdentity>().Where(whereClause).ToList();
}
怎么了?
答案 0 :(得分:1)
请尝试以下代码:
public static class ExpressionTreesExtension
{
public static Expression<Func<T, bool>> EqualExpression<T>(string columnName,object value)
{
ParameterExpression parameterType = Expression.Parameter(typeof(T), "object");
MemberExpression typeColumn = Expression.Property(parameterType, columnName);
ConstantExpression constant = Expression.Constant(value, typeof(string));
BinaryExpression binaryExpression = Expression.Equal(typeColumn, constant);
return Expression.Lambda<Func<T, bool>>(binaryExpression, parameterType);
}
}
代码使用:
Expression<Func<UserIdentity, bool>> whereClause = ExpressionTreesExtension.EqualExpression<UserIdentity>("UserName","John");