Search code examples
c#linqsystem.linq.dynamic

How to write a statement that generates a LIKE T-SQL statement in System.Linq.Dynamic


I am making use of System.Linq.Dynamic and for most of the time it works out great. However I'm trying to get a StartsWith which would generate something like Description LIKE 'test%' in T-SQL.

What I don't seem to find, and documentation is scarce as I noticed, is which statement to write in my code to pass to the Where method of the Dynamic library to generate that LIKE statement.

Things I already tried but didn't work out for me:

.Where("Description LIKE \"test%\"");
.Where("Description < \"test%\"");

But nothing generates the LIKE statement I'm after.


Solution

  • System.Linq.Dynamic translates your text to regular LINQ expressions, and there is no concept of "LIKE" there. How would you write your like in regular LINQ? Something like that:

    ctx.Entity.Where(c => c.Description.StartsWith("test"));
    

    This maps almost exactly to what you should do with dynamic linq:

    // @0 is first parameter, which is "test" in this case
    ctx.Entity.Where("Description.StartsWith(@0)", "test"); 
    

    You can pass value inline too, though I'd recommend to always use parameters like above

    ctx.Entity.Where("Description.StartsWith(\"test\")"); 
    

    You can replace StartsWith with Contains or EndsWith to generate their respective tsql "LIKE" equivalents.