EF Core Like Query — Complete Guide
In this tutorial, you'll learn about EF Core Like Query. We cover key concepts, practical examples, and best practices.
You need to find customers whose name contains "son", or products that start with "Pro". In SQL you use WHERE Name LIKE '%son%'. In EF Core, you can use Contains, StartsWith, EndsWith, or the explicit EF.Functions.Like method.
Wrong
// Client-side evaluation — loads all data first!
var results = db.Customers
.AsEnumerable() // Forces client-side
.Where(c => c.Name.Contains("son"))
.ToList();
Output: SELECT * FROM Customers — all rows loaded into memory. Filtering happens in C#. Terrible for large tables.
Right
// Server-side evaluation — translates to SQL LIKE
var results = await db.Customers
.Where(c => c.Name.Contains("son"))
.ToListAsync();
Output: SELECT * FROM Customers WHERE Name LIKE N'%son%'. Filtering happens on the database server.
Pattern matching methods and their SQL equivalents:
// StartsWith -> LIKE 'prefix%'
var a = db.Products.Where(p => p.Name.StartsWith("Pro"));
// EndsWith -> LIKE '%suffix'
var b = db.Products.Where(p => p.Name.EndsWith("Max"));
// Contains -> LIKE '%substring%'
var c = db.Products.Where(p => p.Name.Contains("book"));
// EF.Functions.Like for custom patterns:
var d = db.Customers.Where(c =>
EF.Functions.Like(c.Name, "[ABC]%son_"));
Prevention
- Use
string.Contains,StartsWith,EndsWithfor simple pattern matching — they translate to LIKE. - Use
EF.Functions.Likefor custom patterns with wildcards (%,_,[chars]). - Use
EF.Functions.Collatefor case-sensitive/insensitive comparisons. - Ensure columns used in LIKE queries are indexed for performance (though LIKE with leading
%does not use standard indexes). - Use full-text search for complex text matching (multiple words, stemming, ranking).
- Avoid
AsEnumerable()orToList()before filtering — this breaks server-side evaluation.
Common Mistakes with core like query
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
LIKE queries are used in DodaTech's customer search functionality. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro