1

Getting Linq Expression error while getting Enum values. I followed different google tricks but not helpful. I'm new to Ef Core I'm 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().

5
  • Could you paste in the actual code, the exception code is useful, but be good to see the actual code too. Commented May 6, 2020 at 8:47
  • Does this answer your question? Using ToString() in LINQ queries? Commented May 6, 2020 at 9:09
  • The query is translated into sql. ToString() is not translatable to sql. Doesn't a user role have a property (column!) like ur.Name? Commented May 6, 2020 at 9:09
  • 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. Commented May 6, 2020 at 9:23
  • 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. Commented May 6, 2020 at 9:39

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.