LINQ to SQL Wildcards

How can I create wildcards for a lambda LINQ To SQL expression?

This is what I have:

var query = from log in context.Logs select log;
foreach (string filter in CustomReport.ExtColsToFilter)
{
    string tempFilter = filter;
    query = query.Where(Log => Log.FormattedMessage.Contains(tempFilter));
}

This works fine until I try to pass character patterns to the filter string. I am experimenting with SqlMethods.Like(), but to no avail.

Filters above are as follows: "<key>NID</key><value>mcass</value>".

I would like to be able to pass such filters: "<key>NID</key><value>%m%</value>"

+3
source share
2 answers

String.Containsactually implemented as an expression LIKEin LINQ to SQL, so these queries will be equivalent:

query = query.Where(Log => Log.FormattedMessage.Contains("m"));
query = query.Where(Log => SqlMethods.Like(Log.FormattedMessage, "%m%"));

SqlMethods.Like , "%m%a%". . , , , T-SQL.

SQL- , :

exec sp_executesql N'SELECT [t0].[ID], [t0].[FormattedMessage]
FROM [dbo].[Log] AS [t0]
WHERE [t0].[FormattedMessage] LIKE @p0',N'@p0 nvarchar(5)',@p0=N'%m%a%'

, String.StartsWith String.EndsWidth SQL LIKE, , .

+8

, , m *, m, , . (m); -, "m".

,

query.ToList(); 

Now you have the whole list of magazines.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1749082/


All Articles