0

我尝试重构以下代码(按类别和搜索词过滤一些数据库记录):

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable
on entry.PrimaryKey equals otherEntry.Field
where category.Any(String.IsNullOrWhiteSpace) 
   || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm)
   || entry.ProductNumber.Contains(searchTerm)
   || otherEntry.Name1.Contains(searchTerm)
   || otherEntry.Name2.Contains(searchTerm)
   || otherEntry.Name3.Contains(searchTerm)
select new {entry.Something, entry.SomethingElse};

看起来像这样:

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable on entry.PrimaryKey equals otherEntry.Field
let searchFields = new[]{entry.ProductNumber, otherEntry.Name1, otherEntry.Name2,/*...*/}
where category.Any(String.IsNullOrWhiteSpace) 
   || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm) 
   || searchFields.Any(field=>field.Contains(searchTerm))
select new {entry.Something, entry.SomethingElse};

不幸的是,LINQ to SQL 似乎无法做到这一点:我ArgumentException从代码中得到一个searchFields.Any(field=>field.Contains(searchTerm))说明

参数value类型错误。预期:System.String.实际:System.String[].

我该如何调整它才能工作?

编辑:对不起,忘了说searchTerm是一个stringcategory是一个string[]

4

2 回答 2

0

我发现的唯一解决方法是将所有要搜索的字段连接到一个字符串中,并检查搜索词是否包含在其中。当然,这可能会返回误报,并且必须在字段之间插入分隔符以防止这种情况发生。

from entry in _DB.TheTable
join otherEntry in _DB.AnotherTable on entry.PrimaryKey equals otherEntry.Field
let searchFields = entry.ProductNumber + otherEntry.Name1 + otherEntry.Name2 
                   + otherEntry.Name3
where category.Any(String.IsNullOrWhiteSpace) 
        || category.Contains(entry.ProductGroup)
where String.IsNullOrWhiteSpace(searchTerm)
        || searchFields.Contains(searchTerm)
select new {entry.Something, entry.SomethingElse};

我仍然愿意寻求更好的解决方案,如果他们提供其他答案,我会接受。与此同时,我已经回到问题中显示的原始版本。

于 2012-07-22T08:20:08.907 回答
0

编辑:这里给出的解决方案不正确

您遇到的问题是包含只能获取字符串值,并且您正在传递字符串 []。我在想也许你可以searchTerm.Contains(field)正确设置Any函数的条件,因为field变量是一个字符串,你正在寻找的值searchTerm 我希望这可以帮助你。再见!

于 2012-07-18T08:46:40.933 回答