'Getting exception while trying to compare enum(converted to string) and a string value obtained from search
Getting
System.InvalidOperationException: 'The LINQ expression 'DbSet 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()
while trying to compare two values - an enum(by converting to string) and a string keyword which I get from a search form in .NET 3 API
query = query.Where(it => it.EnumType.ToString().ToLower().StartsWith(keyword.ToLower());
Help is appreciated.
Solution 1:[1]
Instead of doing this
it => it.EnumType.ToString()
I would suggest you do it the other way around by try converting
keyword.ToLower()
to enum. You can try something like this.
private static bool IsDefined<T>(string value)
{
return Enum.IsDefined(typeof(T), value);
}
public static T GetEnumByString<T>(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
and then write the expression like this:
if (IsDefined<YourEnum>(keyword))
{
query = query.Where(it => it.EnumType == GetEnumByString<YourEnum>(keyword));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sheheryar Sajid |
