0

I wanted to build code to iterate properties of any object and build dynamic where clause in LINQ based on fields that have a valid value. I have it working.

However, in the code below you will see commented lines that use string interpolation and they simply do not work. The comment explains, but examining the generated SQL it is because the WHERE clause is completely wrong. This only happens for decimal fields and the simply string is the one that works.

It is not the end of the world but I am going to lose sleep as to why LINQ generates this . . . any ideas or help? Thanks much!

// TODO: why does the string interpolation not work?
// it outputs BudgetApproved.Equals(115500.00) which for some reason when query is 
// constructed becomes FROM [Tactic] AS [t] WHERE CAST(0 AS bit) = CAST(1 AS bit)

string whereClause = fieldName + " = " + fieldValue;
//string whereClause = string.Format("{0}.Equals({1})", fieldName, fieldValue);
//string whereClause = $"{fieldName}.Equals({fieldValue})";

query = query.Where(whereClause);

UPDATED

Looks like @NetMage suggestion works but it's odd because in immediate window two outputs seem to be the same.

?fieldName + ".Equals(" + fieldValue + ")";
"ExpenseCategoryItemId.Equals(1)"
?string.Format("{0}.Equals({1})", fieldName, fieldValue);
"ExpenseCategoryItemId.Equals(1)"
SmokeRaven
  • 111
  • 7
  • Can you show us the object and Code in context? – Train Jan 20 '20 at 23:07
  • hey @NetMage . . . sql in the comment is sql generated by query as verified using helper method based on [link][https://stackoverflow.com/questions/4899974/how-to-view-linq-generated-sql-statements] i verified in sql profiler that sql is using WHERE clause with bit casting when i create where clause using string interpolation even though in Studio immediate window the `whereClause` has same string value for all three cases. – SmokeRaven Jan 22 '20 at 19:04
  • 1
    Your string interpolation is not the same as your "simple string". What happens if you do `fieldName+".Equals("+fieldValue+")"` as your simple string or `$"{fieldName} = {fieldValue}"` as your interpolated string? What version/flavor of dynamic LINQ are you using to provide the `Where(string)`? – NetMage Jan 22 '20 at 19:28
  • interesting . . . your suggestion worked @NetMage but i am unclear why. see updated post . . . couldn't get markdown to work in comment for the code snippet from immediate window. in immediate window it seems to generate the same value, but yours works and the other does not when i feed it to `.Where` LINQ operator. this is a .net core 3.0 project but for this class i imported the System.Linq.Dynamic.Core assembly v1.0.20 – SmokeRaven Jan 24 '20 at 18:28

0 Answers0