简体   繁体   English

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

[英]How to avoid RelationalEventId.QueryClientEvaluationWarning in EF Core with complex LINQ?

Currently I have a LINQ statement that Entity Framework Core throws a warning: 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语句,其中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.

I have turned this 'throw warning as exception' in the database context initialization to enforce writing LINQ to evaluate on the server side. 我已在数据库上下文初始化中将此“抛出警告作为异常”,以强制执行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;
}

The above statement is used in the following way. 上面的语句以下列方式使用。

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

Is there a way to get this to translate to TSQL and evaluate on the server side? 有没有办法将其转换为TSQL并在服务器端进行评估? Using System.Linq.Expressions ? 使用System.Linq.Expressions吗?


Edit: Follow up question to my answer below, where is good resources for learning System.Linq.Expressions ? 编辑:对下面我的答案进行跟进,哪里有学习System.Linq.Expressions好资源? I understand basic LINQ well but when it comes to building expression tree's, I don't know where to go. 我很了解基本的LINQ,但是在构建表达式树的时候,我不知道要去哪里。

I managed to get it to work by referring to this 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM