Ryan Coyne
Ryan Coyne

Reputation: 21

The LINQ expression could not be translated in EF Core 3.1

I am trying to use EF Core 3.1 to return rows that contain the specified phrase in any column. I am getting the exception:

InvalidOperationException: The LINQ expression 'DbSet
.Where(b => __stringProperties_0 .Any(y => __Functions_1 .Like(
_: y.GetValue( obj: b, index: null).ToString(), matchExpression: __p_2)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

How can I rewrite this query to avoid this exception?

public async Task<List<Table>>
        GetDataAsync(string query)
    {
        var stringProperties = typeof(Table).GetProperties().Where(prop => prop.PropertyType == query.GetType());
        return await _context.Table
             .Where(x => stringProperties
                .Any(y => (EF.Functions.Like(y.GetValue(x, null).ToString(), "%" + query + "%"))))
             .AsNoTracking().ToListAsync();
    }

Upvotes: 2

Views: 4002

Answers (2)

majid
majid

Reputation: 31

var persons = _PersonRepository.TableNoTracking.Where(expression)
                .ProjectTo<PersonSmallInfoDTO>(_mapper.ConfigurationProvider).AsEnumerable();

write .AsEnumerable() end of your code

Upvotes: 0

devcrp
devcrp

Reputation: 1348

I think this query should do it, I'm using EF.Property method here instead of reflection.

return await _context.Table
             .Where(x => stringProperties
                .Any(y => (EF.Functions.Like(EF.Property<string>(x, stringProperties), "%" + query + "%"))))
             .AsNoTracking().ToListAsync();

Hope it helps!

Upvotes: 1

Related Questions