Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Like Operator in Entity Framework?

We're trying to implement the "LIKE" operator in Entity Framework for our entities with string fields, but it doesn't appear to be supported. Has anyone else tried to do something like this?

This blog post summarizes the issue we're having. We could use contains, but that only matches the most trivial case for LIKE. Combining contains, startswith, endswith, and indexof gets us there, but requires a translation between standard wildcards and Linq to Entities code.

like image 248
brien Avatar asked Jun 23 '09 14:06

brien


4 Answers

I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:

where entity.Name.Contains("xyz")

translates to

WHERE Name LIKE '%xyz%'

(Use StartsWith and EndsWith for other behaviour.)

I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)

like image 130
Jon Skeet Avatar answered Nov 15 '22 22:11

Jon Skeet


This is an old post now, but for anyone looking for the answer, this link should help. Go to this answer if you are already using EF 6.2.x. To this answer if you're using EF Core 2.x

Short version:

SqlFunctions.PatIndex method - returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types

Namespace: System.Data.Objects.SqlClient Assembly: System.Data.Entity (in System.Data.Entity.dll)

A bit of an explanation also appears in this forum thread.

like image 21
Yann Duran Avatar answered Nov 16 '22 00:11

Yann Duran


Update: In EF 6.2 there is a like operator

Where(obj => DbFunctions.Like(obj.Column , "%expression%"))
like image 43
Lode Vlaeminck Avatar answered Nov 15 '22 23:11

Lode Vlaeminck


There is LIKE operator is added in Entity Framework Core 2.0:

var query = from e in _context.Employees
                    where EF.Functions.Like(e.Title, "%developer%")
                    select e;

Comparing to ... where e.Title.Contains("developer") ... it is really translated to SQL LIKE rather than CHARINDEX we see for Contains method.

like image 29
Dmitry Pavlov Avatar answered Nov 15 '22 22:11

Dmitry Pavlov