Thursday, August 22, 2013

LINQDataSource Fix: No applicable method 'StartsWith' exists in type 'String' OR No applicable method 'Contains' exists

Symptom:
  • You have created a LinqDataSoruce control on the Visual Studio ASP.NET web page.
  • You have set up fields to be supplied from TextBox control (may be others.) 
  • You have customized the query to use StartsWith or Contains in the Query and the following type of puzzling error appears.
No applicable method 'StartsWith' exists in type 'String'  or
No applicable method 'Contains' exists in type 'String'

Root Cause:

Many people are very confused about this behavior and come to the conclusion to execute some special LINQ call. Apparently it has nothing to do with missing procedure but it's just the Text or control fields set up not correctly.

This is because the Control's ConvertEmptyStringToNull (for example TextBox)  property needs to be adjusted from true to false. Without it, when nothing is typed into the field, it will go out as a null object and then it cannot find the method.

Please note that it appears that this change has to be made to all of the fields in the query. 

Fix:
  • In your LinqDataSource "Where.." editor dialog box, select the (TextBox control(s)).
  • Next find "Show Advanced Properties" link. Click this.



 Then, you will find where to change ConvertEmptyStringToNull configuration.


 Or, you can edit the configuration straight in the page's source like this;


LinqToSQL: How To do a equivalent of Like '%' "Match Everything"

Question:

How can I do a equivalent of LIKE '%' in SQL with LinqToSql?

Answer:

Simply pass an empty string "" to Contains function.

For example,

var patients = from p in ctx.Patients where PatientsName.Contains("");