Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Comparison exception within Entity Framework FirstOrDefault

I'm querying a table using Entity Framework. The first bit of code was what I wrote, the second bit was what ReSharper suggested I refactor it too. The first one gracefully returns null as it should if the key doesn't exist, but the second throws an exception.

This was attempted with 0-1 records in the table (all of the columns are marked as NOT NULL)

Code that works:

context.brandlink.FirstOrDefault(x => x.ManufacturerKey.ToLower() == manufacturerKey.ToLower());

and code that doesn't work:

context.brandlink.FirstOrDefault(x => String.Equals(x.ManufacturerKey, manufacturerKey, StringComparison.InvariantCultureIgnoreCase));

Exception thrown:

Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'

So my question is: what is the difference between the two expressions?

like image 822
Nick Avatar asked Mar 11 '16 21:03

Nick


Video Answer


1 Answers

So my question is: what is the difference between the two expressions?

The diffence is that the later is using the CLR String.Equals Method (String, String, StringComparison) which is not supported by EF according to CLR Method to Canonical Function Mapping while all the methods used in the former (string.ToLower and string equality operator) are supported.

In general you cannot control the string comparisons for EF queries from code because they are controlled by the database.

like image 200
Ivan Stoev Avatar answered Sep 28 '22 14:09

Ivan Stoev