1

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.

Kris van der Mast
  • 16,343
  • 8
  • 39
  • 61

2 Answers2

1

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.

Evk
  • 98,527
  • 8
  • 141
  • 191
  • The one thing I didn't try was the regular .StartsWith() method like I would do it in Linq itself (and basically did before going into System.Linq.Dynamic as things were becoming hugely complex). Thanks! – Kris van der Mast Apr 04 '18 at 14:26
0

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;
mdickin
  • 2,365
  • 21
  • 27