“喜欢”实体框架中的查询
如何使用 edo 实体框架在 ASP.net MVC 中进行通配符文本搜索(如 SQL 的“like”语句)?
我认为这会起作用:
var elig = (from e in _documentDataModel.Protocol_Eligibility_View
where e.criteria.Contains(query)
select e);
但即使搜索肯定在数据库中的查询字符串,它也不会返回任何结果。我做错了什么?
How do I get wildcard text searches (like SQL's "like" statement) in ASP.net MVC using the edo entity framework?
I assumed this would work:
var elig = (from e in _documentDataModel.Protocol_Eligibility_View
where e.criteria.Contains(query)
select e);
But it returns no results even when searching for a query string that's definitely in the database. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
2019 更新
对于 Entity Framework 6.2,您可以使用 DBFunctions
例如:
2019 update
For Entity Framework 6.2 you can use DBFunctions
For example:
这个人为 Linq 做了一个非常好的“WhereLike”扩展,它接受任何通配符,并使用从通配符位置派生的通用方法来比较两个值(其中一个来自表达式)。
http://trentaulous.com/2010 /08/linq-to-entities-wild-card-like-extension-method/
编辑:
文章好像挂了。我将粘贴下面的扩展代码:
This guy made a very nice "WhereLike" extension for Linq that accepts any wildcard character and compares two values (one of which comes from an expression) with a generic method derived from the location of the wildcard.
http://trentacular.com/2010/08/linq-to-entities-wild-card-like-extension-method/
EDIT:
The article seems to be down. I will paste the extention code below:
String.Contains 应该可以正常工作。 SQL 的 LIKE 语句通常通过 String.StartsWith、String.Contains 或 String.EndsWith 处理。
但是,您可能遇到外壳问题。你可以尝试:
String.Contains should work appropriately. SQL's LIKE statement is typically handled via String.StartsWith, String.Contains, or String.EndsWith.
However, it is possible you're having casing issues. You could try:
Linq toEntity 不支持 SqlMethods 方法,但您可以使用字符串函数:
Linq to entities does not support the SqlMethods method, but you could use the string functions instead:
System.Data.Linq.SqlClient 命名空间包含 SqlMethods 类。您可以使用它的 Like 方法,如下所示:
The System.Data.Linq.SqlClient namespace contains the SqlMethods class. You can use it's Like method like this:
我开始使用 Jon Koeter 在另一个似乎不再存在的答案中从博客文章中发布的代码。
然而,我发现它并没有真正正常工作,特别是在使用
IEnumerable
时。也就是说,它使用 ToArray 解析枚举并使用正则表达式进行匹配,而不是内置函数。由于我只想在完成过滤后解析我的
IEnumerable
,因此我做了一些更改以转换为IQueryable
,然后使用其余代码来查找正确的实体框架方法并调用它。这样,查询本身直到稍后才会调用数据库,并且避免了正则表达式的使用。用法:
I started using the code that Jon Koeter posted from the blog post in another answer that no longer appears to exist.
However, I found it didn't really work properly, especially when using an
IEnumerable
. Namely, it was resolving the enumerable usingToArray
and using a regex to match, rather than the built in functions.Since I only want to resolve my
IEnumerable
once I have finished filtering, I made some changes to convert to anIQueryable
then use the rest of the code to find the correct Entity Framework method and call that. This way, the query itself is not called against the database until later, and it avoids the use of a regex.Usage: