如何在复杂的LINQ中避免EF Core中的RelationalEventId.QueryClientEvaluationWarning?

时间:2017-07-10 23:28:03

标签: c# linq-to-sql entity-framework-core

目前我有一个LINQ语句,Entity Framework Core会发出警告:System.InvalidOperationException: Warning as error exception for warning 'RelationalEventId.QueryClientEvaluationWarning': The LINQ expression '(Invoke(__selector_0, [x]).ToString() == __value_1)' could not be translated and will be evaluated locally.

我已在数据库上下文初始化中将此“抛出警告作为异常”转换为强制编写LINQ以在服务器端进行评估。

public async Task<int?> ExistsAsync<TValue>(TestModel entity, Func<TestModel, TValue> selector)
{
    var value = selector(entity).ToString();

    var test = await _context.TestModel.Where(x => selector(x).ToString() == value).Select(x => x.Id).FirstOrDefaultAsync();

    return test;
}

上述声明以下列方式使用。

var id = await _service.ExistsAsync(new TestModel {Name = name}, x => x.Name);

有没有办法让它转换为TSQL并在服务器端进行评估?使用System.Linq.Expressions

修改:跟进我的answer下面的问题,哪里有良好的学习资源System.Linq.Expressions?我理解基本的LINQ,但是当涉及构建表达式树时,我不知道该去哪里。

1 个答案:

答案 0 :(得分:0)

我设法通过引用此answer来使其工作。

public async Task<int?> ExistsAsync<TValue>(TestModel entity, Expression<Func<TestModel, TValue>> expression)
{
    var selector = expression.Compile();
    var value = selector(entity);

    var predicate = Expression.Lambda<Func<Equipment, bool>>(Expression.Equal(expression.Body, Expression.Constant(value)), expression.Parameters);

    var id= await _context.TestModel.Where(predicate).Select(x => x.Id).FirstOrDefaultAsync();

    return id;
}