简体   繁体   English

动态LINQ在哪里查询

[英]Dynamic LINQ where query

I'm using dynamic LINQ to create a query from given columns the user selects for a given search. 我正在使用动态LINQ从用户为给定搜索选择的给定列创建查询。

eg simplified code ex: 例如简化代码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 此代码生成给定的SQL查询

(([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 这是正确的,虽然我想要做的是能够使用通配符,当我尝试输入比如说百分比字符时,生成的SQL是

(([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? 有没有办法在使用动态L2S时在搜索字符串中使用通配符?

Regards 问候

You can try using .StartsWith || .EndsWith || .Contains 您可以尝试使用.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. 由于您使用的是Linq to Sql,因此您可以使用SqlMethods帮助程序类。

One of the methods is Like which maps onto the SQL LIKE clause. 其中一种方法是Like映射到SQL LIKE子句。 If you need it, it is more flexible than using .StartsWith etc 如果你需要它,它比使用.StartsWith等更灵活

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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