简体   繁体   中英

Dynamic LINQ where query

I'm using dynamic LINQ to create a query from given columns the user selects for a given search.

eg simplified code ex:

var counter = 0;
var predicate = string.Empty;
foreach(var field in selectedFields)
{
    predicate += field + ".Contains(@" + counter + ") ||"; 
    // logical OR, without it the SQL generates AND
}    
predicate = predicate.Remove(predicate.LastIndexOf("||", 2));
query = query.Where(predicate, searchvalues);

This code generates the given SQL query

(([t0].[Field1] LIKE 'searchstring') OR ([t0].[Field2] LIKE 'searchstring'))

Which is correct, albeit what i want to do is be able to use wildcards, when i try to enter let's say, a percent character, the SQL generated is

(([t0].[field1] LIKE 'searchstring' ESCAPE '~') OR ([t0].[field2] LIKE 'searchstring' ESCAPE '~'))

Is there a way to use wildcards in the searchstring while using dynamic L2S?

Regards

You can try using .StartsWith || .EndsWith || .Contains .StartsWith || .EndsWith || .Contains

That might solve the problem.

Since you're using Linq to Sql then you can make use of the SqlMethods helper class.

One of the methods is Like which maps onto the SQL LIKE clause. If you need it, it is more flexible than using .StartsWith etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM