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

c# entity-framework-core linq-to-sql

Question

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.

I have turned this 'throw warning as exception' in the database context initialization to enforce writing LINQ to evaluate on the server side.

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? Using System.Linq.Expressions?


Edit: Follow up question to my answer below, where is good resources for learning System.Linq.Expressions? I understand basic LINQ well but when it comes to building expression tree's, I don't know where to go.

1
0
7/11/2017 4:55:49 PM

Accepted Answer

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;
}
0
7/11/2017 4:34:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow