I am currently converting some SQL to C# code against Entity Framework and have come up against an issue with a keyword search query.
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. 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".
I have tried writing a string contains method against 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".
How would I be able to get the same results as the SQL contains query?
You have to write a custom SQL function and call this one from 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
var query = this.DataContext.Search("my search string");
Try Using 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.