Thursday, March 1, 2018

Using String.Equals() not working as intended error in Lamda

You may get error :

"

Incorrect number of arguments supplied for call to method 'Boolean Equals

"

When trying to use string.Equals() in lamda, this issue can be resolved by using 

Compare instead of Equals.


Explanation: "When using LINQ to Entities, it will automatically convert it to LINQ to SQL. And if the database field you are doing a .Equals on does not have a collate of NOCASE (SQLite in my example) then it will always be case-sensitive. In otherwords, the database defines how to do the string comparison rather than code." per  https://stackoverflow.com/questions/5080727/string-equals-not-working-as-intended/22978905


Example:

  //does NOT work when coalesce is DataColumn on

                var rows = db.WorkflowStartQueues.Where(x => (x.WorkflowStatus != null) && string.Equals(x.WorkflowStatus, workflowStatus, StringComparison.CurrentCultureIgnoreCase)).ToList();

                //DOES work not db reliant

                var rows2 = db.WorkflowStartQueues.Where(x => string.Compare(x.WorkflowStatus, workflowStatus, true) == 0).ToList();

                


More info:

Case insensitive string equality comparison

Use the String:Compare(string,string,bool) method to explicitly express a case-insensitive complete string equality operation. The generated SQL will not depend on the case-sensitivity of the current database collation.
LINQ: … .Where( x => string.Compare(x.FirstName, simpleParam, true) == 0 ) …
SQL: … where upper(a.FirstName) = upper(@p1) …

No comments:

Post a Comment