[英]Converting a SQL contains query for Entity Framework
I am currently converting some SQL to C# code against Entity Framework and have come up against an issue with a keyword search query. 我目前正在根据Entity Framework将一些SQL转换为C#代码,并且遇到了关键字搜索查询的问题。
The (very) simplified query ultimately looks like this: (非常)简化的查询最终看起来像这样:
SELECT * FROM SomeTable
WHERE CONTAINS(Col1, Col2, Col3, '"word"')
As per the docs https://docs.microsoft.com/en-us/sql/t-sql/queries/contains-transact-sql this method searches for fuzzy or precise matches on words or phrases. 根据文档https://docs.microsoft.com/zh-cn/sql/t-sql/queries/contains-transact-sql,此方法搜索单词或短语上的模糊或精确匹配。 So if I ran a search for the keyword of "word" I will get results where Col1, Col2 or Col3 have the instance of "word". 因此,如果我搜索“ word”的关键字,我将获得Col1,Col2或Col3具有“ word”实例的结果。
I have tried writing a string contains method against Entity Framework: 我曾尝试针对Entity Framework写一个包含方法的字符串:
Context.Where(i => i.Col1.Contains("word") || i.Col2.Contains("word") || i.Col3.Contains("word"))
However this produces a wildcard like query '%word%' and returns results that are not relevant, for example I get matches on "word" and "swords". 但是,这会产生一个类似查询'%word%'的通配符,并返回不相关的结果,例如,我在“ word”和“ swords”上获得了匹配项。
How would I be able to get the same results as the SQL contains query? 如何获得与SQL包含查询相同的结果?
You have to write a custom SQL function and call this one from C#. 您必须编写一个自定义SQL函数,然后从C#调用此函数。
For example: 例如:
CREATE FUNCTION [dbo].[Search](@Search nvarchar(4000))
RETURNS TABLE
AS
RETURN (
SELECT
*
FROM
[dbo].[SomeTable]
WHERE
CONTAINS(Col1, Col2, Col3, @Search)
)
GO
When it is generated to EDMX use it like this 当它生成到EDMX时,像这样使用它
var query = this.DataContext.Search("my search string");
Try Using SqlMethods.Like 尝试使用SqlMethods.Like
Example: 例:
Context.Where(x=> SqlMethods.Like(x.Col1,'word')
||SqlMethods.Like(x.Col2,'word')).ToList();
You can find SqlMethods Under System.Data.Linq.SqlClient; 您可以在System.Data.Linq.SqlClient下找到SqlMethods。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.