Dynamic Linq placeholders don't work properly

c# dynamic-linq linq

Question

I've got the following query:

query.Where("@0 != null && @1.ToString().Contains(@2)", 
            searchedColumnName, searchedColumnName, searchedValue);

And it doesn't work (There are multiple records that should be retreived).

For example, let searchedColumnName == "MY_COLUMN", and searchedValue == "8". When I debug into Dynamic Linq methods, the resulting LambdaExpression expression is:

{Param_0 => ((Convert("MY_COLUMN") != null) AndAlso "MY_COLUMN".ToString().Contains("8"))}

Now, If I don't use placeholders, like:

query.Where(searchedColumnName + " != null && " +
            searchedColumnName + ".ToString().Contains(\"" + searchedValue +"\")");

the LambdaExpression is:

{Param_0 => ((Param_0.MY_COLUMN != null) AndAlso Param_0.MY_COLUMN.ToString().Contains("8"))}

and it works.

I guess it means I use the placeholders incorrectly?

1
0
12/20/2017 8:18:32 AM

Accepted Answer

Yes, there is a problem with the way you write the placeholder.

Your column name "MY_COLUMN" is considered as the string, not as a column.

So I think, you can not use the placeholder for the column name here. You can use below code:

.Where(searchedColumnName+ " = @0", searchedValue);

For C#6 .Where($"{searchedColumnName} = @0", searchedValue);

Refer this link. It explains the dynamic INQ filter very well:

https://q-a-assistant.info/computer-internet-technology/dynamic-linq-filter-never-retrieves-correct-results-uwp-xaml/676258

1
12/20/2017 8:53:26 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow