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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With