0
votes

Getting Linq Expression error while getting Enum values. I followed different google tricks but not helpful. I'm new to Ef Core Im returning Enum Type userRoles to var roles by this line.But i got null. var roles = await _context.Roles.Where(r => userRoles.Any(ur => ur.ToString() == r.Name)).ToListAsync();

System.InvalidOperationException: The LINQ expression 'DbSet .Where(r => __userRoles_0 .Any(ur => ur.ToString() == r.Name ))' 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().

1
Could you paste in the actual code, the exception code is useful, but be good to see the actual code too. - mrdnk
Does this answer your question? Using ToString() in LINQ queries? - Luis Gouveia
The query is translated into sql. ToString() is not translatable to sql. Doesn't a user role have a property (column!) like ur.Name? - René Vogt
while this work fine in core 2.0 but in 3.1.3 its not working. @RenéVogt userrole include user and role class along their id. - Uttam Paudel
Lots of people are having issues with code that worked in Core 2.0 and does not work in Core 3.0 nor Core 3.1. - jdweng

1 Answers

1
votes

As I understand, the userRoles variable holds some in-memory collection (like List, array etc.) containing some custom Enum values which you want to use as a filter for an entity having string property.

EF Core has very limited support of in-memory collections inside LINQ to Entities query. Basically collections of primitive types and Enumerable.Contains.

So what you can do in this specific case is to convert the custom Enum values collection to string collection containing the desired names outside the EF Core query (1) and then use it with Contains operator inside (2):

var userRoleNames = userRoles.Select(ur => ur.ToString()); // (1)
var roles = await _context.Roles
    .Where(r => userRoleNames.Contains(r.Name)) // (2)
    .ToListAsync();