【问题标题】:InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expressionInvalidOperationException:尝试评估 LINQ 查询参数表达式时引发异常
【发布时间】:2020-07-09 01:57:41
【问题描述】:

我有一个问题,在源代码中,查询 LINQ。从 2.2 升级到 .net core 3.1 后。

    public IQueryable<Data.Model.Content> GetAll()
    {
        return dbContext.Content.Include(a => a.ContentTemplate);
    }

    public bool ExistsSlug(int id, string name)
    {
        return GetAll()
            .Any(x => x.Name.ToLower() == name.ToLower() && x.Id != id);
    }

错误:

NullReferenceException: Object reference not set to an instance of an object.

lambda_method(Closure )

InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.

Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.GetValue(Expression expression, out string parameterName)

    return GetAll().Any(x => x.Name.ToLower() == name.ToLower() && x.Id != id);

System.Linq.Queryable.Any<TSource>(IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)

lambda_method(Closure , object , object[] )

Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)

【问题讨论】:

    标签: c# .net linq entity-framework-core .net-core-3.1


    【解决方案1】:

    我已经使用 .net core 3.1 创建了您正在使用的确切场景。

    唯一产生相同错误的测试用例是当我发送 (NAME STRING NULL)

    您可以通过在查询中添加条件语句来绕过此问题,如下所示:

    GetAll().Any(x=> (string.IsNullOrEmpty(name) || x.Name.ToLower() == name.ToLower()) && x.Id  != id);
    

    【讨论】:

    • 在 where 子句中调用空对象方法或属性时会出现空引用异常
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 2023-01-03
    相关资源
    最近更新 更多