4

To convert the SQL LIKE query to LINQ which having "%"(percentage) operators both at the start and end of the string, we use the Contains() method.

e.g.

SELECT * FROM [User] WHERE Username LIKE '%test%'

The equivalent LINQ is:

var users = (from usr in Context.Users
            where usr.Username.Contains("test")
            select usr).ToList();

What will be equivalent of the below query which contains multiple "%"(percentage) operators in the input text?

SELECT * FROM [User] WHERE Username LIKE '%test%email%'

Any help is appreciated.

Note: The query will be executed in the EntityFramework(version 6.1.3)

Dukhabandhu Sahoo
  • 1,394
  • 1
  • 22
  • 44
  • 1
    Sounds like a Regex to me. – Rotem Jun 14 '18 at 08:30
  • 4
    You don't mentioned your environment, but for example EF have `Like` function: `entity => EF.Functions.Like(entity.Name, $"%{searchname}%")` – Fabio Jun 14 '18 at 08:30
  • Possible duplicate of [Like Operator in Entity Framework?](https://stackoverflow.com/questions/1033007/like-operator-in-entity-framework) – CodeNotFound Jun 14 '18 at 08:35
  • You'll find your solution in [this answer](https://stackoverflow.com/a/47442276/797882) at the duplicated link. – CodeNotFound Jun 14 '18 at 08:36
  • @CodeNotFound DbFunction.Like() worked like charm for EF 6.2.0. However, I noticed the EntityFramework is in version 6.1.3 in the target project. The Like() is not available in "6.1.3". Is there any alternate solution for this? I have updated the note in the original question to avoid the confusion. – Dukhabandhu Sahoo Jun 14 '18 at 09:00
  • Do all your best to upgrade to 6.2.0. There is no breaking changes. I did it in the past weeks and no modifications needed. Don't forget that EF 6 follows [semantic versioning](https://semver.org/). – CodeNotFound Jun 14 '18 at 09:07
  • 1
    Ok, thanks for the help. – Dukhabandhu Sahoo Jun 14 '18 at 09:15

1 Answers1

9

Posting the comments given by @Fabio and @CodeNotFound as answer for reference.

In EntityFramework version 6.2.0:

var users = (from usr in Context.Users
            where DbFunctions.Like(usr.Username, "%test%email%")
            select usr).ToList();
Dukhabandhu Sahoo
  • 1,394
  • 1
  • 22
  • 44