6

I know the .Contains() method does like LIKE %therm%, the .StartsWith() method does like LIKE therm% and the .EndsWith() method like LIKE %therm but...

Is there a way to do like below on **Linq to Entities**?

SELECT * FROM [dbo].[Users] WHERE Name LIKE 'rodrigo%otavio%diniz%waltenberg'

PS: I'M USING LINQ TO ENTITIES. NOT LINQ TO SQL

  • Possible duplicate of [How to use SQL 'LIKE' with LINQ to Entities?](http://stackoverflow.com/questions/3095781/how-to-use-sql-like-with-linq-to-entities) – Michael Freidgeim Mar 17 '17 at 02:14

3 Answers3

2

This should do the trick.

from u in context.users
    where System.Data.Linq.SqlClient.SqlMethods.Like(
        u.Name, 
        "rodrigo%otavio%diniz%waltenberg")
    select u

Edit:
It turns out this only works with LINQ2SQL, not LINQ2Entities. Linq SqlMethods.Like fails suggests that you can use Where directly on the table.

Community
  • 1
  • 1
Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108
  • 3
    Exception: LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method, and this method cannot be translated into a store expression. – Rodrigo Waltenberg Oct 20 '10 at 20:26
  • @Rodrigo: Hmmm, l2e works to close to l2s to be confusing... I updated my answer with a linq to another question that might be helpful. – Albin Sunnanbo Oct 21 '10 at 05:03
2

Yes, you can do this with ESQL/Query Builder syntax:

var matching = Context.Users.Where("it.Name LIKE 'rodrigo%otavio%diniz%waltenberg'");
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
-1

How about using regular expressions with your LINQ statement? Something like the following:

        RegularExpressions.Regex p 
             = new RegularExpressions.Regex("rodrigo%otavio%diniz%waltenberg");

        using (DataContext.MyDataContext context = new MyDataContext())
        {
            var result = from u in context.users
                      where p.IsMatch(u.name)
                      select u;
        }
Terry C
  • 79
  • 4
  • 4
    Exception: LINQ to Entities does not recognize the method 'Boolean IsMatch(System.String)' method, and this method cannot be translated into a store expression. – Rodrigo Waltenberg Oct 21 '10 at 23:14