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

82 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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.

2
On

I haven't used this library, but they have an example that generates a LIKE statement. Does that fit your use?

For posterity, here's the code:

var q = from c in db.Customers
        where SqlMethods.Like(c.CustomerID, "C%")
        select c;