如何检查字符串是否包含Entity Framework中的列表中的任何字符串? [英] How do you check if a string contains any strings from a list in Entity Framework?

查看:113
本文介绍了如何检查字符串是否包含Entity Framework中的列表中的任何字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var searchTerms 

我正在尝试搜索一个数据库,查看一个字符串是否包含搜索字词列表的元素。 = new List< string> {car,232};
var result = context.Data.Where(data => data.Name.Contains(searchTerms)||
data.Code.Contains(searchTerms));

如果searchTerms是一个字符串,但我一直在试图让它与



本质上,我需要SQL,这将表示

  SELECT * FROM Data 
WHERE名称LIKE'%car%'
或名称LIKE'%232%'
或代码LIKE'%car%'
OR代码LIKE'%232 %'

linq其中list包含任何列表似乎是关闭的事情,我可以找到的情况。



其中(data => searchTerms.Contains(data.Name)|| searchTerms.Contains(data.Code)只会将精确匹配带回搜索词列表。



我已经尝试在Entity Framework中搜索多个关键字搜索,并用尽了这些努力。有没有办法实现我的目标?

解决方案

你可以尝试使用任何方法,我不知道是否支持,但值得尝试:

  var result = context.Data.Where(data => searchTerms.Any(x => data.Name.Contains(x))|| 
searchTerms.Any(x => data.Code.Contains(x));

如果这样给你 NotSupportedException ,你可以添加 AsEnumerable before Where 以获取所有记录并在内存中执行查询而不是DB。


I am trying to search a database to see if a string contains elements of a list of search terms.

var searchTerms = new List<string> { "car", "232" };
var result = context.Data.Where(data => data.Name.Contains(searchTerms) ||
                                        data.Code.Contains(searchTerms));

This would work if searchTerms was a string but I've been trying to get it to work with a list of strings.

Essentially I need SQL which would say

SELECT * FROM Data
WHERE Name LIKE '%car%'
OR Name LIKE '%232%'
OR Code LIKE '%car%'
OR Code LIKE '%232%'

linq where list contains any in list seems to be the closes thing I could find to the situation.

Where(data => searchTerms.Contains(data.Name) || searchTerms.Contains(data.Code) only brings back exact matches to the search terms list.

I have tried searching for multiple keyword search in Entity Framework also and have exhausted that effort. Is there any way to achieve what I am aiming for?

解决方案

You can try using Any method, I'm not sure whether it's supported but it's worth trying:

var result = context.Data.Where(data => searchTerms.Any(x => data.Name.Contains(x)) ||
                                        searchTerms.Any(x => data.Code.Contains(x));

If this gives you NotSupportedException you can add AsEnumerable before Where to fetch all records and execute the query in memory rather than DB.

这篇关于如何检查字符串是否包含Entity Framework中的列表中的任何字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆