When you need SQL-style LIKE '%keyword%' behavior in LINQ to SQL or Entity Framework, the simplest approach is to use Contains(). It automatically translates to a SQL LIKE query.
Modern LINQ / ASP.NET Core Example
[Route("search")]
[HttpPost]
public IActionResult Search(string search)
{
var posts = _db.Posts
.Where(x => x.Body.Contains(search))
.Where(x => x.Title.Contains(search))
.ToArray();
ViewBag.SearchCriteria = search;
ViewBag.TagView = new TagView(_db);
return View(posts);
}
Contains() is translated by EF Core into:
WHERE Body LIKE '%search%' AND Title LIKE '%search%'
Older LINQ to SQL Approach (Deprecated)
Before Contains() was fully supported, developers often used SqlMethods.Like to achieve SQL wildcard searches.
using System.Data.Linq.SqlClient;
var result =
from b in db.Blogs
where SqlMethods.Like(b.Title, "%" + keyword + "%")
|| SqlMethods.Like(b.Body, "%" + keyword + "%")
orderby b.AddedDate descending
select b;
This method still works in legacy LINQ-to-SQL applications, but modern EF and ASP.NET Core applications should use Contains(), StartsWith(), or EndsWith() for cleaner, more maintainable code.
Both approaches ultimately generate SQL LIKE queries, but Contains() is the recommended modern solution.
Comments (0)
Please sign in to comment.