LINQ to Entities无法识别方法’System.String Split(Char )’方法,
我正在尝试实现一种方法,其中存储在数据库中的活动关键字(用逗号分隔)与用逗号分隔的给定字符串匹配。
public List SearchByMultipleKeyword(string keywords) { string[] keyword = keywords.Split(','); var results = (from a in Entities.TblActivities where a.Keywords.Split(',').Any(p => keyword.Contains(p)) select a).ToList(); return results; }
我收到以下错误:
LINQ to Entities does not recognize the method 'System.String[] Split(Char[])' method, and this method cannot be translated into a store expression.
对于不涉及太多关键字和太多行的查询,您可以实现这种简单快速的解决方案。 您可以通过反复优化结果轻松绕过Splitfunction,如下所示:
public List SearchByMultipleKeyword(string keywords) { string[] keywords = pKeywords.Split(','); var results = Entities.TblActivities.AsQueryable(); foreach(string k in keywords){ results = from a in results where a.Keywords.Contains(k) select a; } return results.ToList(); }
您无法使用entity framework执行此操作,如错误消息所示。
但是,有选择。
一种选择是认识到,如果关键字存储为A,B,C,D
,那么x
就在那里
a.Keywords.StartsWith(x + ",") || a.Keywords.Contains("," + x + ",") || a.Keywords.EndsWith("," + x)
如果x
本身不包含,
那就有效。 缺点是这将对表或包含Keywords
列的索引进行全面扫描。
另一种选择是规范化您的数据库。 毕竟,您在活动和关键字之间存在一对多的关系。 然后将其建模为:除了Activities
表(没有Keywords列)之外,还有一个包含两列的KeyWords
表,一个活动表的外键和一个keyword
列。 这将允许您在keyword
列上添加索引,这可以使查询超快。
UPDATE
我重新阅读了您的问题,并注意到您没有测试关键字相等性,只是Contains
。 如果是这样,你为什么不这样做呢?
a.Keywords.Contains(x)
Entity Framework不支持String.Split
。 这只是因为SQL中没有等价物。
一个解决方案是:
- 在数据库中定义自定义函数本文提出了几个解决方案: http : //sqlperformance.com/2012/07/t-sql-queries/split-strings
- 使用
[EdmFunction]
属性声明此函数可由LINQ to Entities使用,如下所述: 如何从EF LINQ查询调用DB函数?
LINQ to Entities尝试将您的LINQ查询转换为SQL。 由于它不知道如何在SQL查询中执行String.Split
,因此失败。
这意味着除非您想编写String.Split
的SQL实现, String.Split
只能在LINQ to对象中执行,这意味着您需要先将所有数据加载到内存中,然后执行where
子句。 一种简单的方法是使用.ToList()
:
var results = (from a in Entities.TblActivities select a).ToList(); //Results are now in memory results = results.Where(a => a.Keywords.Split(',').Any(p => keyword.Contains(p))).ToList(); //This uses LINQ-to-objects
是的你可以这样做:
public List SearchByMultipleKeyword(string keywords) { string[] keywordsSeparated = keywords.Split(','); var results = (from a in Entities.TblActivities where keywordsSeparated.Any(keyword => a.Keywords.Contains(keyword)) select a).ToList(); return results; }
不确定,但你可以尝试:由于错误似乎在寻找一个数组,这可能会有效。
上述就是C#学习教程:LINQ to Entities无法识别方法’System.String Split(Char )’方法,分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)
string[] keyword = keywords.Split(new char[] {','}); var results = (from a in Entities.TblActivities where a.Keywords.Split(new char[] {','}).Any(p => keyword.Contains(p)) select a).ToList();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。
如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1025041.html