Linq可查询表达式树:SqlException:'&'附近的语法不正确

时间:2017-06-13 13:45:45

标签: linq tree expression

我收到错误:{SqlException:'&'附近的语法不正确我似乎无法弄明白。我有一个课程QuestionResult(见下文)。

public class QuestionResult
{
    public int Id { get; set; }
    public float? Result { get; set; }
    public string ResultText { get; set; }

    //Foreign Keys & Connections
    public virtual SurveyResult SurveyResult { get; set; }
    public virtual Question Question { get; set; }
    public int QuestionId { get; set; }
    public int SurveyResultId { get; set; }
}

我希望通过QuestionId&过滤结果,例如{QuestionId == 48&&结果> = 24}。问题似乎是使用Expression.And。我尝试了这个测试,没有使用它,只使用其中一个条件,它运行良好。我之前使用过Expression.And,但它已经有效了。

public static List<int> GetIdList()
{ 
    IQueryable<QuestionResult> questionResultList = _context.QuestionResult.AsQueryable();
    var questionResult = Expression.Parameter(typeof(QuestionResult), "qr");
    MemberExpression questionId = Expression.Property(questionResult, "QuestionId");
    MemberExpression result = Expression.Property(questionResult, "Result");
    var conditionA = Expression.Equal(questionId, Expression.Constant(48));
    var conditionB = Expression.GreaterThanOrEqual(result, Expression.Convert(Expression.Constant(24), result.Type));
    var and = Expression.And(conditionA, conditionB);
    var predicateBody = Expression.Lambda<Func<QuestionResult, bool>>(and, questionResult);

    MethodCallExpression query = Expression.Call(
        typeof(Queryable),
        "Where",
        new Type[] { questionResultList.ElementType },
        questionResultList.Expression,
        predicateBody
    );
    var questionResultIdList = questionResultList.Provider.CreateQuery<QuestionResult>(query).Select(i => i.Id).ToList();

    return questionResultIdList;
}

你能看到我出错的地方吗?在运行之前调试查询显示:

{value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1 [SurveyV3.Models.DatabaseModels.QuestionResult])。其中(qr =&gt;((qr.QuestionId == 48)And(qr.Result&gt; =转换(24))))}

看起来对我来说。我一直在使用此处和此Microsoft页面上的问题寻求帮助https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/expression-trees/how-to-use-expression-trees-to-build-dynamic-queries

谢谢,Oj

1 个答案:

答案 0 :(得分:0)

  
    

var和= Expression.And(conditionA,conditionB);

  

Expression.AndAlso执行按位 AND操作。

您希望If( (Test-Connection servername -Count 1).StatusCode -eq 0) 执行逻辑AND。