Linq to EF4 Contains 方法的意外行为
在对人员进行查询时,此语句应返回许多姓氏中包含“And”的结果 -
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.Contains("And");
它不返回任何结果。如果我们将其更改为 -
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.Contains("Anderson");
我们会得到所有姓安德森的人。
显然它被转换为 SQL 作为 Equals 而不是 Like 。此外,我们将其修改为 -
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.FirstOrDefault()
.Contains("And");
返回所有姓氏中任何地方有“And”的人,不幸的是它只检查该人的第一个姓氏。
var results = repository.GetQuery().Where(p => p.Names
.Any(n=> n.LastName
.Contains("And"));
工作正常,但我们不能按照我们想要的方式使用它。
On a query of people, this statement should return a number of results that have "And" in their last name-
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.Contains("And");
It returns no results. If we change it to-
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.Contains("Anderson");
We get all people who has a last name of Anderson.
Obviously it is being translated to SQL as an Equals instead of a Like . Furthermore we modified it to be-
var results = repository.GetQuery().Where(p => p.Names
.Select(n=> n.LastName)
.FirstOrDefault()
.Contains("And");
That returns all the people who have "And" anywhere in there last name, unfortunately it only checks the first lastname of the person.
var results = repository.GetQuery().Where(p => p.Names
.Any(n=> n.LastName
.Contains("And"));
Works properly, but we cannot use this the way we would like to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您正在尝试执行此操作:
.Contains() 方法仅适用于完全匹配。您可以使用 Linq to SQL 并指定您要查找的确切 SQL,但使用存储过程可能会更好。
这看起来会有一些帮助: LINQ to SQL和通配符搜索
It looks like you are trying to do this:
The .Contains() method only works with exact matches. You can use Linq to SQL and specify the exact SQL you are looking for, but that would probably be better with a stored procedure.
This looks like it would be of some assistance: LINQ to SQL and wildcard searches
长期以来一直致力于这个动态搜索问题......我无法透过树木看到森林。
这不起作用,因为它是一个 IEnumerable.Contains 方法,仅返回完美匹配。
这是有效的,因为它使用的是 String.Contains 方法。
它们是两种不同的 Contains 方法。我们使用动态搜索进行最后一项工作。
Been working on this dynamic search problem so long...I could not see the forest through the trees.
This does not work because it is an IEnumerable.Contains method which only returns a perfect match.
This works because it is using a String.Contains method.
They are two differnent Contains methods. We go the last one working with our Dynamic Searches.