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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.