Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Dynamic LINQ (System.Linq.Dynamic) for LIKE operation?

Can any body tell me how can I use a LIKE operator using System.Linq.Dynamic?

I need to add more than one LIKE expression in my dynamic where query

/*
var query =
db.Customers.
Where("CityName Like @0 or CityName Like @1", "London", "USA")
*/
var query =
db.Customers.
Where("CityName Like @0 or CityName Like @1%", "London", "USA")

thanks heaps

like image 713
Kiarash Avatar asked Jan 05 '11 01:01

Kiarash


People also ask

Can you use LINQ on dynamic?

The Dynamic source file includes a helper library that allows you to express LINQ queries using extension methods that take string arguments instead of type safe operators. To use the Dynamic Expression API, you could simply copy/paste the Dynamic source file in your project.

What is System LINQ dynamic?

The Dynamic LINQ library exposes a set of extension methods on IQueryable corresponding to the standard LINQ methods at Queryable, and which accept strings in a special syntax instead of expression trees.

What is Dynamic query in C#?

Instead of using language operators or type-safe lambda extension methods to construct your LINQ queries, the dynamic query library provides you with string-based extension methods that you can pass any string expression into.


3 Answers

Try using simply "CityName.Contains(@1)" this will convert to the proper lambda since its a method invocation on an accessible type.

something like:

var query =
db.Customers.
Where("CityName.Contains(@0) or CityName.Contains(@1)", "London", "USA")

Just tested it with the sample app that comes with the dynamic library and it generates the LIKE operator

like image 109
Jaime Avatar answered Oct 21 '22 06:10

Jaime


You can use .StartsWith(), .EndsWith() and .Contains() which will generate LIKE SQL with trailing, leading and surrounding wildcards respectively. Don't know of a way to generate a statement with an embedded wildcard tho.

like image 39
Arne Claassen Avatar answered Oct 21 '22 07:10

Arne Claassen


This will allow the LIKE operator on integer fields:

.Where(searchField + ".ToString().Contains(@0)", searchString);
like image 43
Dino Avatar answered Oct 21 '22 08:10

Dino