Link to home
Start Free TrialLog in
Avatar of Camillia
CamilliaFlag for United States of America

asked on

Rewrite this LINQ query

I'm getting an error with this LINQ query.

1. This works

 public async Task<List<TextValuePair>> ByCategory(string category)
        {
            var codes = await DataContext.LookupCodes
                .Where(lc => lc.Category == category)
                .OrderBy(lc => lc.Code)
                .Select(d => new TextValuePair { Value = d.Code, Text = string.IsNullOrWhiteSpace(d.Description) ? d.Code : d.Description })
                .ToListAsync();
            return codes;
        }

Open in new window

2. I changed it to pass in a List

 public async Task<List<TextValuePair>> ByCategoryList([FromBody] List<string> category)
        {
            var codes = await DataContext.LookupCodes
                
                .Where(lc => lc.Category.Any(c => category.Contains(lc.Category)))
                .OrderBy(lc => lc.Code)
                .Select(d => new TextValuePair { Value = d.Code, Text = string.IsNullOrWhiteSpace(d.Description) ? d.Code : d.Description })
                .ToListAsync();
            return codes;
        }

Open in new window


3. This is the error

System.InvalidOperationException: The LINQ expression 'DbSet<LookupCode>()\r\n    .Where(l => l.Category\r\n        .Any(c => __category_0.Contains(l.Category)))' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'


4. This how the data looks like


User generated image

Maybe something like this

https://stackoverflow.com/questions/68737681/the-linq-expression-could-not-be-translated-either-rewrite-the-query-in-a-form

ASKER CERTIFIED SOLUTION
Avatar of Snarf0001
Snarf0001
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Camillia

ASKER

Thanks. I've been looking into the error and you're right - EF can't translate the "Any".


Let me try what you have and I'll post back. 

You're the best :) it worked. I was making it harder than it is.

Awesome, glad it's working :)