Updated on
LINQ has no Like method, but EF Core still writes SQL LIKE for us. It turns Contains, StartsWith and EndsWith into LIKE patterns, and EF.Functions.Like sends a pattern of our own, wildcards and all, straight to the database.
We’ll look at the SQL each one produces on SQL Server, and at what goes wrong when the search term comes from a user.
Let’s start.
Sample Application
We will start with a .NET 10 console application, and install the Entity Framework Core (EF Core) SQL Server provider, Microsoft.EntityFrameworkCore.SqlServer. If you are unfamiliar with EF Core, please first refer to the Entity Framework Core Series.
Setup Logging
In order for us to see the exact query generated by EF Core, we can configure logging to the application. First, we copy Usings.cs, BlogDbContext.cs and Models/Article.cs from the sample repository into our project. They hold the global usings, a BlogDbContext with an Articles set, and an Article class with an Id and a Title. Then, let’s prepare a local database with EF Core and set up a logging method inside the Program.cs file:
string sqlConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;Database=BlogDb;Integrated Security=True";
var contextOption = new DbContextOptionsBuilder<BlogDbContext>()
.UseSqlServer(sqlConnectionString)
.LogTo(Console.WriteLine, [DbLoggerCategory.Database.Name], LogLevel.Information)
.Options;
var blogDbContext = new BlogDbContext(contextOption);
blogDbContext.Database.EnsureCreated();
We specify the Console.WriteLine as an output method and the DbLoggerCategory.Database with Information level as the logging scope in the LogTo method. By doing this, we can see the actual T-SQL statements in the console.
LogTo is one of several ways to see the SQL that EF Core generates. Later on, we’ll also use ToQueryString(), which shows parameter values next to the SQL.
Which LINQ Methods Translate to SQL LIKE?
Three string methods and one EF Core function cover every LIKE query we’re likely to write.
Contains("n") becomes LIKE N'%n%', StartsWith("n") becomes LIKE N'n%', and EndsWith("n") becomes LIKE N'%n'. EF Core adds the % wildcards for us. It does that inside Where, Count, FirstOrDefault and the other LINQ methods that take a predicate.
These three treat the search term as plain text. If the term contains %, _ or [, EF Core escapes it, so StartsWith("_n") looks for titles that really begin with an underscore.
When we want the wildcards to work, we call EF.Functions.Like(x.Title, "_n%"). EF Core passes that pattern to SQL Server as it is, so _, [] and [^] keep their SQL meaning.
None of this works on a plain List<string>. It only applies to queries that EF Core translates to SQL, as the sections below show.
Use the Contains Method to Generate SQL Like Operator in a Query
EF Core translates the Contains method into a LIKE operator. So, let’s see an example of that:
List<Article> articles = blogDbContext.Articles.Where(x => x.Title.Contains("n")).ToList();
We use the Contains method as a predicate for the Where method, and it states the condition. When we execute the application, we can find the T-SQL statement in the log:
SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'%n%'
As we can see, using the Contains method inside the Where method enables us to generate the SQL LIKE operator with the '%n%' search term.
Of course, we can use other LINQ methods with the Contains method as a parameter to generate the same LIKE queries.
Let’s see how to do that with the Count method:
int articleCounts = blogDbContext.Articles.Count(x => x.Title.Contains("n"));
After we run our sample application, we can see the translated query in the console window:
SELECT COUNT(*) FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'%n%'
Or the FirstOrDefault method:
Article? firstArticle = blogDbContext.Articles.FirstOrDefault(x => x.Title.Contains("n"));
This also generates a similar query with a LIKE operator:
SELECT TOP(1) [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'%n%'
These methods, like many other LINQ methods, will generate the SQL query with a LIKE operator.
Use the StartsWith Method to Generate SQL Like Operator in a Query
If we want to check whether a sequence starts with a certain term, we can use the StartsWith method in C#. EF Core translates the StartsWith method into a LIKE operator as a forward match.
So, let’s see an example of that:
articles = blogDbContext.Articles.Where(x => x.Title.StartsWith("n")).ToList();
Now, we can start the application and inspect the result in the console window:
SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'n%'
We can see the LIKE operator in the WHERE clause with the 'n%' search term.
Use the EndsWith Method to Generate SQL Like Operator in a Query
Likewise, if we want to check whether a sequence ends with a certain term, we can use the EndsWith method.
Let’s see another example that uses the EndsWith method:
articles = blogDbContext.Articles.Where(x => x.Title.EndsWith("n")).ToList();
Once again, we can run our application and inspect the generated query:
SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'%n'
As we can see, EF Core translates the EndsWith method into a query that uses the LIKE operator with the '%n' search term.
Use EF.Functions.Like Method for Other Wildcard Characters
So far, we learned how to translate the LINQ query into the LIKE operator with the % wildcard. But, SQL Server supports other wildcard characters such as _ , [], and [^] for more complex pattern matchings. To use these wildcard characters, we need the EF.Functions.Like method. But why can’t we use the previous methods?
Let’s examine it first:
articles = blogDbContext.Articles.Where(x => x.Title.StartsWith("_n")).ToList();
We specify the "_n" as the pattern with the StartsWith method by assuming it generates the LIKE operator with the '_n%' pattern.
Let’s run the application and inspect the generated query:
SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'\_n%' ESCAPE N'\'
As a result, it escapes the _ wildcard, which is not what we want here.
Instead, let’s use the EF.Functions.Like method:
articles = blogDbContext.Articles.Where(x => EF.Functions.Like(x.Title, "_n%")).ToList();
After we run the application again, let’s inspect the output:
SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE N'_n%'
It doesn’t escape the wildcard this time. We can use the all supported wildcard characters by using the EF.Functions.Like method. One caveat is if we switch the provider, it may behave differently as that provider may not understand the pattern exactly the same as the SQL Server.
Case is part of that. LIKE follows the column’s collation, and SQL Server’s default collation ignores case, so with a row titled NOP in our table, Contains("n") returns it too. Microsoft’s API reference for EF.Functions.Like says “the semantics of the comparison will depend on the database configuration”. The in-memory provider in our tests compares the way .NET does, so the same query there is case-sensitive.
Passing a StringComparison doesn’t help either. EF Core can’t translate Contains(term, StringComparison.OrdinalIgnoreCase) and throws an InvalidOperationException instead. For in-memory strings, our article on checking if a string contains a substring, ignoring case covers the options.
What Happens When the Search Term Comes From User Input?
So far, every search term has been a constant. In a real application, it usually comes from a search box. Let’s put it in a variable and give it a character that means something to LIKE:
string searchTerm = "50%"; articles = blogDbContext.Articles.Where(x => x.Title.Contains(searchTerm)).ToList();
EF Core now sends a parameter instead of a literal. To see the parameter’s value next to the SQL, we call ToQueryString() on the same query:
DECLARE @searchTerm_contains nvarchar(4000) = N'%50\%%'; SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE @searchTerm_contains ESCAPE N'\'
EF Core escaped the % in our term and wrapped the result in its own wildcards. The query finds titles that contain the text “50%” and nothing else. StartsWith and EndsWith behave the same way, with @searchTerm_startswith and @searchTerm_endswith parameters.
EF.Functions.Like doesn’t do this for us, and it can’t. It has no way to tell our wildcards from the user’s. Here’s the version that goes wrong, a “starts with” pattern built from the same term:
string pattern = $"{searchTerm}%";
articles = blogDbContext.Articles.Where(x => EF.Functions.Like(x.Title, pattern)).ToList();
This time, the parameter holds the pattern exactly as we built it:
DECLARE @pattern nvarchar(4000) = N'50%%'; SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE @pattern
The value still travels as a parameter, so this isn’t SQL injection. But the user’s % is now a wildcard, and the query returns a “50 tips” article as well as “50% off”. A user who types a single % gets every row in the table.
To fix it, we escape the term ourselves and tell EF.Functions.Like which escape character we used. A small helper class in its own file, LikePattern.cs, is enough:
public static class LikePattern
{
public static string Escape(string term) =>
term.Replace(@"\", @"\\")
.Replace("%", @"\%")
.Replace("_", @"\_")
.Replace("[", @"\[");
}
It escapes the backslash first, so the backslashes it adds afterwards stay single. Then we pass the escape character as the third argument:
string safePattern = $"{LikePattern.Escape(searchTerm)}%";
articles = blogDbContext.Articles.Where(x => EF.Functions.Like(x.Title, safePattern, @"\")).ToList();
Now EF Core adds an ESCAPE clause, and only our trailing % acts as a wildcard:
DECLARE @safePattern nvarchar(4000) = N'50\%%'; SELECT [a].[Id], [a].[Title] FROM [Articles] AS [a] WHERE [a].[Title] LIKE @safePattern ESCAPE N'\'
Here’s how the five calls treat a search term of 50% on SQL Server:
| LINQ call | Pattern SQL Server receives | Are %, _ and [ in the term escaped? |
|---|---|---|
x.Title.Contains(searchTerm) | %50\%% | Yes, by EF Core |
x.Title.StartsWith(searchTerm) | 50\%% | Yes, by EF Core |
x.Title.EndsWith(searchTerm) | %50\% | Yes, by EF Core |
EF.Functions.Like(x.Title, pattern) | the pattern as written | No |
EF.Functions.Like(x.Title, safePattern, @"\") | the pattern as written, plus ESCAPE N'\' | Only what we escape ourselves |
If the user is supposed to type wildcards, as in an admin search screen, the two-argument EF.Functions.Like is the right call. Everywhere else, the string methods are simpler and safe by default.
Does C# Have a LIKE Operator?
No. C# has no LIKE operator, and string has no Like method. Visual Basic has a Like operator, but C# never got one.
What we use instead depends on where the data lives. Inside an EF Core query, Contains, StartsWith, EndsWith and EF.Functions.Like all end up as SQL LIKE, and the database does the matching.
On an in-memory collection, the three string methods are ordinary .NET calls and work as they always do. For a pattern they can’t express, such as “the second letter is n”, a regular expression takes the place of LIKE: ^.n does the job of _n%.
EF.Functions.Like is the one that catches people out. It has no in-memory implementation, so calling it on a List<string> throws an InvalidOperationException instead of filtering. The same thing happens when part of an EF Core query has to run on the client.
Here’s the regular expression version on a small list:
List<string> titles = ["nop", "mnp", "lmn", "abc"];
List<string> secondLetterN = titles.Where(t => Regex.IsMatch(t, "^.n")).ToList();
Console.WriteLine(string.Join(", ", secondLetterN));
It prints mnp, the same title EF.Functions.Like(x.Title, "_n%") returns in our tests. If the pattern syntax is new to you, our article on regular expressions walks through it.
Conclusion
In this article, we’ve learned how to use the SQL LIKE operator with LINQ in C#. We learned about different ways to generate the LIKE operator with LINQ methods and similar translated queries those methods produce.
We also saw that the string methods escape a user’s wildcards for us, while EF.Functions.Like needs us to escape them ourselves.
Tested with .NET 10 (SDK 10.0.302, runtime 10.0.10) and EF Core 10.0.14 on SQL Server LocalDB.






