Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core 3.0 translating string.Equals ordinalIgnoreCase correctly

Before EF Core 3.0 this worked fine (evaluated on server+client):

var exists = await _context.Countries.AsNoTracking().AnyAsync(x => x.CountryCode.Equals(country.CountryCode, StringComparison.OrdinalIgnoreCase));

What is the best/preferred method to translate the string.Equals(str, StringComparison.OrdinalIgnoreCase)-part now in EF Core 3.0, so that the query evaluates only on the server side.

var exists = await _context.Countries.AsNoTracking().AnyAsync(x => x.CountryCode.ToUpper() == country.CountryCode.ToUpper());

or

var exists = await _context.Countries.AsNoTracking().AnyAsync(x => x.CountryCode.ToLower() == country.CountryCode.ToLower());

or

var exists = await _context.Countries.AsNoTracking().AnyAsync(x => x.CountryCode.ToUpperInvariant() == country.CountryCode.ToUpperInvariant());

or

var exists = await _context.Countries.AsNoTracking().AnyAsync(x => x.CountryCode.ToLowerInvariant() == country.CountryCode.ToLowerInvariant());

or something else?

like image 647
juFo Avatar asked Oct 31 '19 09:10

juFo


People also ask

How to parse SQL in EF Core?

Starting with EF Core 3.0, EF Core will not try to parse the SQL. So if you are composing after FromSqlRaw/FromSqlInterpolated, then EF Core will compose the SQL by causing sub query. So if you are using a stored procedure with composition then you will get an exception for invalid SQL syntax.

Why can't I use stringcomparison in EF Core?

In addition, .NET provides overloads of string.Equals accepting a StringComparison enum, which allows specifying case-sensitivity and a culture for the comparison. By design, EF Core refrains from translating these overloads to SQL, and attempting to use them will result in an exception.

Why are the method names overloaded in EF Core?

Before EF Core 3.0, these method names were overloaded to work with either a normal string or a string that should be interpolated into SQL and parameters.

How are expressions evaluated in EF Core?

Starting with 3.0, EF Core only allows expressions in the top-level projection (the last Select () call in the query) to be evaluated on the client. When expressions in any other part of the query can't be converted to either SQL or a parameter, an exception is thrown.


1 Answers

You should not do that, nor use the accepted answer method, you should just use String.Equals() without parameters and configure your database collation, during creation or migration.

like image 60
L.Trabacchin Avatar answered Sep 19 '22 14:09

L.Trabacchin