cm44
cm44

Reputation: 111

Entity Framework Core 3.1.1 : Where query could not be translated. Either rewrite the query in a form that can be translated,

After I upgraded Entity Framework Core from 2 to 3.0.0 and 3.1.1, my code broke on Linq .Where clauses.

I wouldn't use .AsEnumerable<ExampleObject().

For example:

List<string> exampleFilter = new List<string>(){"filter1" , "filter2"};

var IQueryable<ExampleObjects> objs = repository.GetAll().Where(wh => exampleFilter.Contains(wh.Name));//HERE1

// here code broke in v3.0.0 when apply where with contains
var count = await objs.CountAsync();  

After upgrade 3.0.0 to 3.1.1 the last bug was solved but now my code broke a few lines down:

objs = objs.Where(wh => MatchFilters(wh.Name, wh.Description,filters));

// here the code broke in v3.1.1
count = await objs.CountAsync();  

This is my exception:

Where(a => ClassName.MatchEveryFilter(
name: a.Name,
code: a.Code,
filters: __filters_0))'
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()

My code:

private bool MatchFilters(string name, strin description , List<strings> filters)
{
    foreach(var filter in filters)
    {
        if(!name.Contains(filter) && !description.Contains(filer))
             return false;
    }

    return true;
}

How can I rewrite my code on where with function MatchFilters inside?

Upvotes: 4

Views: 2156

Answers (1)

Gabriel Llorico
Gabriel Llorico

Reputation: 1803

you could chain your filters

var query = context.TableName.AsQueryable();

foreach(var filter in filters)
{
    query = query.Where(x => !x.Name.Contains(filter) && !x.Description.Contains(filter))
}

var result = query.ToList();

Upvotes: 1

Related Questions